Replace part of a JSON with other (using a string token)

You can use SelectToken to select any item in the JSON object hierarchy. It supports JSONPath query syntax. It returns a JToken corresponding to the value of the selected item, or null if not found. That JToken in turn has a Replace(JToken replacement) method. Thus you can do:

var o1 = JObject.Parse(json);
var o2 = JObject.Parse(json2);

var path = "client.spouse";
o1.SelectToken(path).Replace(o2.SelectToken(path));

var path2 = "client.email";
o1.SelectToken(path2).Replace(o2.SelectToken(path2));

Leave a Comment