Jsonpath for array length

Given json such as

{"arr1" : [1,2,3], "arr2" : []} 

where it is known that there are arrays named arr1 and arr2, is there a jsonpath expression for the length of the array that will work for both empty and non-empty arrays?

I made several attempts using the JsonPath library for Google code, noting:

 JsonPath.read(json, "arr1.length") 

but it gives an error saying arrays have no attributes.

I am looking for one string path that resolves the length of an array, and not a subsequent call to an intermediate element, e.g.

 JsonPath.read(json, "arr1").length // useless to me 

Any level of expression complexity is acceptable.

In the context, I want to pass a test case with path / value pairs, which works great for values, but I cannot validate the size of the array using this template.

+6
source share
2 answers

If the length of the array is required only for approval, then the json-path-assert artifact can be used with JsonPath . Here is an example written in Groovy:

 @Grab('com.jayway.jsonpath:json-path:0.9.1') @Grab('com.jayway.jsonpath:json-path-assert:0.9.1') import com.jayway.jsonpath.JsonPath import static com.jayway.jsonassert.JsonAssert.* import static org.hamcrest.MatcherAssert.assertThat import static org.hamcrest.Matchers.* def json = /{ "arr1": [1,2,3], "arr2": [] }/ with(json).assertThat( "arr1", hasSize(3) ) .assertThat( "arr2", hasSize(0) ) .assertThat( "arr2", emptyCollection() ) 

Make sure the statement fails with a different array size. The best part is the use of the Hamcrest Matcher API , which opens the door to a flexible and wide variety of statements.

Length cannot be obtained from an AFAIK path expression.

+8
source

@dmahapatro is right in saying that

Length cannot be obtained from path expression

But , if you only need to access a specific element (let them say the last element of the array), you can still use:

 {"arr1": [1,2,3], "arr2": [{"name": "a"}, {"name": "b"}]} arr1[(@.length-1)] // returns "3" arr2[(@.length-1)].name // returns "b" 

You can also perform more complex queries, but for this I suggest you familiarize yourself with the plugin.

+1
source

Source: https://habr.com/ru/post/972301/


All Articles