JsonPath: How to check if a field has some value or not through JsonPath?

Saurabh Patil picture Saurabh Patil · Jun 17, 2016 · Viewed 16.1k times · Source

I am finding it a little difficult to understand how to write a jsonpath that will tell me whether there is some value present or not in the field.

For example: Consider this json:

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}

And if I write: $.phoneNumbers[?(@.type.length>0)]

It gives me this result:

'0' ...
  'type' => "iPhone"
  'number' => "0123-4567-8888"
'1' ...
  'type' => "home"
  'number' => "0123-4567-8910"

I did this here: http://jsonpath.com/

So if suppose I want to know if there is any value in the number field inside the phonenumber or if it's empty , then what should be my jsonpath? I tried various things, but couldn't figure it out.

Thanks!

Answer

mkoertgen picture mkoertgen · Jun 29, 2016

You may use the exists-filter ?(@.<field>) like so

$.phoneNumbers[?(@.number)].number

This will give you all numbers with any non-null value are, i.e.

"phoneNumbers": [
{
  "type"  : "iPhone",
  "number": "0123-4567-8888"
},
{
  "type"  : "home",
  "number": ""
}]

will only return the first result

'0' => "0123-4567-8888"

regardless whether the number-field is completely missing, null or an empty string "".

I learned this from some of Newtonsoft.Json's JPath-Unit-Tests, cf.: JPathExecutTests.ExistsQuery()