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!
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.
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.
Jayway JsonPath is a Java port of Stefan Goessner JsonPath implementation.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With