Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

jsonpath

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!

like image 812
Saurabh Patil Avatar asked Jun 17 '16 07:06

Saurabh Patil


People also ask

How do you evaluate a JSON path?

You can open up a window to evaluate JSONPath expressions by going to Edit -> Find -> "Evaluate JSONPath Expression...". If a JSON file is open, it will use this file to evaluate the expression. If you have JSONPath expressions as Strings in code, use "inject language" and say this is a JSONPath expression.

What is difference between JSON & JSONPath?

JSONPath creates a uniform standard and syntax to define different parts of a JSON document. JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. This topic is best understood by seeing it in action. We have created a web page which can help you evaluate a JSONPath.

What is Jayway JSONPath?

Jayway JsonPath is a Java port of Stefan Goessner JsonPath implementation.

What is JSONPath and XPath?

JSONPath is a query language for JSON, similar to XPath for XML. XPath expression can be used to extract information from an XML document by evaluating given expression.


1 Answers

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()

like image 75
mkoertgen Avatar answered Sep 25 '22 11:09

mkoertgen