Search code examples
c#json.netjsonpath

Newtonsoft update JObject from JSON path?


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.


Solution

  • Json paths (and xpaths for that matter) are used to get items from a hierarchy, not to set them. You need to get the parent object using the JSON path then set the property through normal means.

    var parent = jObject.SelectToken("root.item[0]");
    parent["myProperty"] = "My New Value";