Is there a way to extract conditionally a value from a JSON object with a JSONPath based on another value inside the same object?

Viewed 28

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#.

1 Answers

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
Related