Search code examples
c#jsonjson.netjsonpath

How to check multiple keys in JsonPath


I am trying to find an object in a JSON array using JsonPath. Here is my JSON:

[
  {
    "bpm": "766",
    "time": "20:14:57",
    "confidence": "0"
  },
  {
    "bpm": "766",
    "time": "20:14:57",
    "confidence": "0"
  },
  {
    "bpm": "767",
    "time": "20:14:33",
    "confidence": "0"
  }
]

I am using SelectToken with the following JsonPath query to try to find a JSON object using two keys bpm and time. There is supposed to be an and operator between bpm and time.

Here is my query:

$.[?(@.bpm=='767',@.time=='20:14:33')]

But I'm getting an error saying there is an unexpected character , after '767'. What am I doing wrong?


Solution

  • In Newtonsoft's implementation of JsonPath, the and operator is a double ampersand &&, not a comma ,. Change your expression as shown below and it should work properly:

    var array = JArray.Parse(json);
    var obj = array.SelectToken("$.[?(@.bpm=='767' && @.time=='20:14:33')]");
    

    Fiddle: https://dotnetfiddle.net/gpU56p