3

I have a little utility where we extract values from JSON using JObject.SelectToken(path). We need to determine the paths at run-time. Works perfectly.

What I now need to do is to write back into the JSON (JObject or other) using the same path string. I've hunted and searched and I can't quite find if there is anything that does this quite as cleanly as SelectToken does for reading.

(I'm also stuck in 3.5 CF)

For example, something like:

... JObject read in already ...

var theJToken = theJObject.SelectToken("animals.cat[3].name");
theTJoken.SetValue("Bob"); // Of course this doesn't exist

... serialize it ... 
1
  • As my first "minuses", can you share why? Commented Aug 10, 2015 at 21:31

1 Answer 1

8

JToken.SelectToken actually returns a JToken which can be modified using JToken.Replace. You can use that to replace the node within your JSON object, mutating the original object.

JObject o = JObject.Parse(@"{ 'cats': [
                { 'name': 'cat 1' },
                { 'name': 'cat 2' },
                { 'name': 'cat 3' } ] }");

// get the token
JToken secondCatName = o.SelectToken("cats[1].name");

// replace the name
secondCatName.Replace("meow");

// and the original object has changed
Console.WriteLine(o.ToString());
// { "cats": [ { "name": "cat 1" }, { "name": "meow" }, { "name": "cat 3" } ] }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. That seems to have done the trick. I didn't see Replace() and might not have thought to use it because I didn't realize that the JToken would implicitly take a string or whatever I sent in. Always learning!

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.