1. Overview
In this quick tutorial, we’ll explore how to use JsonPath to count objects and arrays in a JSON document.
JsonPath provides a standard mechanism to traverse through specific parts of a JSON document. We can say JsonPath is to JSON what XPath is to XML.
2. Required Dependencies
We’re using the following JsonPath Maven dependency, which is, of course, available on Maven Central:
<dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.4.0</version> </dependency>
3. Sample JSON
The following JSON will be used to illustrate the examples:
{ "items":{ "book":[ { "author":"Arthur Conan Doyle", "title":"Sherlock Holmes", "price":8.99 }, { "author":"J. R. R. Tolkien", "title":"The Lord of the Rings", "isbn":"0-395-19395-8", "price":22.99 } ], "bicycle":{ "color":"red", "price":19.95 } }, "url":"mystore.com", "owner":"baeldung" }
4. Count JSON Objects
The root element is denoted by the Dollar symbol “$”. In the following JUnit test, we call JsonPath.read() with the JSON String and the JSON path “$” that we want to count:
public void shouldMatchCountOfObjects() { Map<String, String> objectMap = JsonPath.read(json, "$"); assertEquals(3, objectMap.keySet().size()); }
By counting the size of the resulting Map, we know how many elements are at the given path within the JSON structure.
5. Count JSON Array Size
In the following JUnit test, we query the JSON to find the array containing all books under the items element:
public void shouldMatchCountOfArrays() { JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]"); assertEquals(2, jsonArray.size()); }
6. Conclusion
In this article, we’ve covered some basic examples on how to count items within a JSON structure.
You can explore more path examples in the official JsonPath docs.
As always, the code examples can be found in the GitHub repository.