how to set the value of a json path using json.net

c#, json, json.net

Solution

    public string SetPreference(string username, string path, string value)
    {
        if (!value.StartsWith("[") && !value.StartsWith("{"))
            value = string.Format("\"{0}\"", value);

        var val = JObject.Parse(string.Format("{{\"x\":{0}}}", value)).SelectToken("x");

        var prefs = GetPreferences(username);

        var jprefs = JObject.Parse(prefs ?? @"{}");

        var token = jprefs.SelectToken(path) as JValue;

        if (token == null)
        {
            dynamic jpart = jprefs;

            foreach (var part in path.Split('.'))
            {
                if (jpart[part] == null)
                    jpart.Add(new JProperty(part, new JObject()));

                jpart = jpart[part];
            }

            jpart.Replace(val);
        }
        else
            token.Replace(val);

        SetPreferences(username, jprefs.ToString());

        return jprefs.SelectToken(path).ToString();
    }

Problem

I am trying to set an arbitrary path in a JSON structure and I am having difficulty figuring out how to do a simple set value... What I would like is some method like, SetValue(path,value) which operates like SelectToken, but creates the path if it does not exist and sets the value. ``` public void SetPreference(string username, string path, string value) { var prefs = GetPreferences(username); var jprefs = JObject.Parse(prefs ?? @"{}"); var token = jprefs.SelectToken(path); if (token != null) { // how to set the value of the path? } else // how to add the path and value, example {"global.defaults.sort": { "true" }} } ``` what I mean by `global.defaults.sort` path is actually `{ global: { defaults: { sort: { true } } } }`

Original source