7

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 } } } }

1 Answer 1

10
    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();
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but it needs modification to handle JSON arrays , i'll post code sample when i finish it
So the answer is essentially: "Newtonsoft doesn't do it, but you can interpret the jsonpath yourself"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.