0

I have the following JSON object

{"id":"15", "value":1}

I want to extract the value 1 if and only if id == 15.

The most relevant expression I tried was

$?(@.id=="15").value

but it doesn't seem to work, I only obtain no match.

I use json.net in C#.

Bene Tleilax
  • 190
  • 12
  • 1
    The [JSONPath proposal](https://goessner.net/articles/JsonPath/) is somewhat ambiguous about whether conditional queries should work on the root object, however Json.NET's support for JSONPath queries is only specified to work for objects **inside arrays** not objects inside objects or root objects. ... – dbc Sep 21 '22 at 20:52
  • 1
    ... For confirmation see this comment by JamesNK: [JSONPath scripts not executing correctly for objects #1256](https://github.com/JamesNK/Newtonsoft.Json/issues/1256#issuecomment-289134144): *I'm not sure about this. Nothing in the JSONPath says that filters should apply to objects.* Sometimes workarounds can be found, see [here](https://stackoverflow.com/a/45298348/3744182) or [here](https://stackoverflow.com/a/39453636/3744182). – dbc Sep 21 '22 at 20:52
  • 1
    See also [How to make SelectTokens() select root element if jsonpath expression evaluates to true](https://stackoverflow.com/q/68983688) and [JsonPath: Selecting root level field if satisfies a condition](https://stackoverflow.com/q/25031187) which make it clear that the standard doesn't clearly define whether it should be possible to filter the root object itself. I think a query like yours could be made to work if your object were inside an array, i.e. `[{"id":"15", "value":1}]`. – dbc Sep 21 '22 at 20:56

1 Answers1

2

You have to learn what is jsonPath for.It is impossible to use jsonPath to extract something from one only property. this is much easier

var jObj=JObject.Parse(json);

int? value = jObj["id"].ToString() == "15" ? (int)jObj["value"] : null; //1

json path is working only with collections, so move your object inside of the array

    var json = "[{\"id\":\"15\", \"value\":1}]";
    
    var jArr = JArray.Parse(json);
    
    int id= (int) jArr.SelectToken("$[?(@.id=='15')].value"); //1
    //or
    int id = (int) jArr.SelectToken("$[?(@.id=='15')]")["value"]; //1
Serge
  • 40,935
  • 4
  • 18
  • 45
  • I understand. Thank you for your answer, but I'm "stuck" in the sense that I can only manipulate the json through a jsonPath and no other way. I understand after reading @dbc comments now that what I want to do is just impossible with jsonPath. – Bene Tleilax Sep 22 '22 at 14:13