Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SelectTokens pattern for element according to sub-element value (C#, Json.NET)

The JSON structure that is being investigated looks like:

string jsonText 
    = @"{ ""348975"":{""name"":""nam1"",""value"":1}"
    + @", ""876132"":{""name"":""nam2"",""value"":2}"
    + @", ... }";

One needs to select the value element for the object that has a given name. For the above JSON, suppose the given name is "nam2", the returned valued would have to be 2. One tried to use:

JObject jsonObject = JObject.Parse(jsonText);
string searchName = "nam2";
JToken myValue = jsonObject.SelectToken("[?(@.name=" + searchName + ")].value");

and similar JSON path strings, but with no success. It is possible and simple to do with iteration over all the elements, but one needs to know if it can be done with SelectToken.

Please assist. Thank you!

like image 850
Gilad Rave Avatar asked Dec 12 '25 23:12

Gilad Rave


1 Answers

I wasn't able to get this to work using JSONPath, I tried the following which seems like it should work:

$.*[?(@.name == 'nam1')]

However it doesn't. You can use LINQ to JSON instead though if your only goal is to do it in one line:

JToken myValue = jsonObject.SelectTokens("$.*")
    .SingleOrDefault (jt => jt["name"]
    .Value<string>() == searchName); 
like image 98
Andrew Whitaker Avatar answered Dec 14 '25 13:12

Andrew Whitaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!