Jaime
Jaime

Reputation: 5965

Newtonsoft's JObject: read any property using a string expression

I have a JObject and want to get any property or array element coming from a string expression.

I already know how to do it explicitly, like: jObject["a"][0]["b");

But I would like to do something like: jObject("a[0].b");

The reason is that I am allowing the user to specify what to gather from the JSON object, rather than hardcoding the operation.

Upvotes: 0

Views: 109

Answers (1)

Eser
Eser

Reputation: 12546

You can use SelectToken

string json = @"{a:[{b:1}]}";
var jobj = JObject.Parse(json);
var token = jobj.SelectToken("a[0].b");
Console.WriteLine(token);

Upvotes: 2

Related Questions