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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With