Newtonsoft update JObject from JSON path?

Viewed 6288

I am aware of using the select tokens function to pass a json path. For example:

JObject jObect = JObject.Parse("{some json string}");
JToken jToken = jObject.SelectToken("root.item[0].myProperty"); 

What I am looking for is a simple manner to update the original JObject at the given JSON path?

jObject[jsonPath] = "My New Value" 

Obviously that takes an object key and not JSON path. Thanks.

3 Answers

I think @dbc has given a good extension to allow us to update the json object values. Can find his answer here.

But, I would put here a solution that I made with the help of above answer:

public static class JsonExtensions
{
    public static JObject ReplacePath<T>(this JToken root, string path, T newValue)
    {
        if (root == null || path == null)
        {
            throw new ArgumentNullException();
        }

        foreach (var value in root.SelectTokens(path).ToList())
        {
            if (value == root)
            {
                root = JToken.FromObject(newValue);
            }
            else
            {
                value.Replace(JToken.FromObject(newValue));
            }
        }

        return (JObject)root;
    }
}

What you can do it, using above method, you can pass the JObject, the jsonPath and the value you want to replace. So, in your case the calling method would look like this:

var jsonObj = JObject.Parse("{some json string}");   
jsonObj = JsonExtensions.ReplacePath(jsonObj,
                                         "$. root.item[0].myProperty",
                                         "My New Value");

Hope this will work for you!

You can find some examples I put in fiddle (https://dotnetfiddle.net/ZrS2iV)

You can replace function of Jtoken to update the value.

var parseResponse = JToken.Parse(jsonString);
//This commented code will update all the myproperty value in the item array
//var selectedPath = parseResponse.SelectToken("$.root.item[*].myProperty");
var selectedPath = parseResponse.SelectToken("$.root.item[0].myProperty");
if(selectedPath!=null){
selectedPath.Replace(newValue);
}

Related