Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size using jsonpath expression - Stefan Goessner JsonPath

I'm having a problem with finding an array or list size using Stefan Goessner's JsonPath. I'm using the version json-path-2.0.0.

My jsonpath expression is $.orders.length and JSON looks something like this:

{    "orders" : [      ...    ]  }

Its failing with the following error:

com.jayway.jsonpath.PathNotFoundException: Property ['length'] not found in path $['orders'] 

And I tried with $.orders.length() too which is again failing with the below error:

com.jayway.jsonpath.PathNotFoundException: Property ['length()'] not found in path $['orders']

Please suggest me how to get the length of the array using Goessner's JsonPath expression.

[EDIT] Following is how I'm obtaining the configuration:

    com.jayway.jsonpath.Configuration conf = com.jayway.jsonpath.Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);     DocumentContext documentContext = JsonPath.using(conf).parse(orderJson);     Object val = documentContext.read(jsonPathExpression); 
like image 605
Nagendra Varma Avatar asked May 01 '16 09:05

Nagendra Varma


People also ask

What is JsonPath expression?

JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. The "root member object" in JsonPath is always referred to as $ regardless if it is an object or array. JsonPath expressions can use the dot–notation.

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.

What is the difference between JSON and 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.


1 Answers

It seems that support for returning the length() of an array was only added in version 2.1.0 of the jayway json-path library.

Based on some quick tests, the $.orders.length() expression seems to work with both version 2.1.0 and version 2.2.0, so I think you just need to upgrade your dependency version in order to fix the error you are seeing.

like image 56
andersschuller Avatar answered Sep 17 '22 14:09

andersschuller