JSONPath: Getting Array Length
A guide to counting elements in JSON data structures
The Problem: Counting Dynamic Data
When validating API responses or parsing large JSON files, you often need to know how many items are in a list (e.g., "How many orders did the user place?"). JSONPath offers a standardized way to query this.
Method 1: The .length() Function
Syntax:
$.store.book.length()
Many JSONPath implementations (like Jayway used in Java) support a built-in
.length() function that returns the size of an array.
Example JSON
{
"store": {
"book": [
{ "category": "reference" },
{ "category": "fiction" },
{ "category": "history" }
]
}
}Query
$.store.book.length()Result
3Method 2: Using Postman Tests
In Postman execution scripts, standard JSONPath doesn't always have a strict
.length() endpoint. Instead, you parse the array and check its Javascript length
property.
var jsonData = pm.response.json();
var numberOfBooks = jsonData.store.book.length;
pm.expect(numberOfBooks).to.eql(3);Common Pitfalls
Standardization Issues: JSONPath is not as strictly standardized as XPath. Some
libraries support
.length(), others require you to retrieve the array and count it
in the host language (Java, Python, JS).
Aggregators: In libraries like Jayway, functions like
length(),
min(), and max() are "aggregators" and must be the final part of the
path.