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:


3. Sample JSON

The following JSON will be used to illustrate the examples:

                "author":"Arthur Conan Doyle",
                "title":"Sherlock Holmes",
                "author":"J. R. R. Tolkien",
                "title":"The Lord of the Rings",

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.

Course – LS (cat=JSON/Jackson)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:


res – REST with Spring (eBook) (everywhere)