David David - 3 months ago 54
JSON Question

JMeter: How to count JSON objects in an Array using jsonpath

In JMeter I want to check the number of objects in a JSON array, which I receive from the server.

For example, on a certain request I expect an array with 5 objects.


After reading this: count members with jsonpath?, I tried using the following JSON Path Assertion:

  • JSON Path: $

  • Expected value: hasSize(5)

  • Validate against expected value = checked

However, this doesn't seem to work properly. When I actually do receive 5 objects in the array, the response assertion says it doesn't match.

What am I doing wrong?
Or how else can I do this?


Although JSONPath Extractor doesn't provide hasSize function it is still can be done.

Given example JSON from the answer by PMD UBIK-INGENIERIE, you can get matches number on book array at least in 2 ways:

1. Easiser (but fragile) way - using Regular Expression Extractor.

As you can see, there are 4 entries for category like:

{ "category": "reference",
{ \"category\": \"fiction\"

If you add a Regular Expression Extractor configured as follows:

JSON Regex

It'll capture all the category entries and return matches number as below:

JSON Regex Matches

So you will be able to use this ${matches_matchNr} variable wherever required.

This approach is straightforward and easy to implement but it's very vulnerable to any changes in response format. If you expect that JSON data may change in foreseeable future continue to the next option.

2. Harder (but more stable) way - calling JsonPath methods from Beanshell PostProcessor

JMeter has Beanshell scripting extension mechanism which has access to all variables/properties in scope as well as access to underlying JMeter and 3rd-party dependencies APIs. In this case you can call JsonPath library (which is under the hood of JsonPath Extractor) directly from Beanshell PostProcessor.

import com.jayway.jsonpath.Criteria;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.JsonPath;

Object json = new String(data);
List categories = new ArrayList();
Filter filter = Filter.filter(Criteria.where("category").in(categories));
List books = JsonPath.read(json, "$.store.book[?]", new Filter[] {filter});

vars.put("JSON_ARRAY_SIZE", String.valueOf(books.size()));

The code above evaluates JSONPath expression of $.store.book[?] against parent sampler response, counts matches number and stores it into ${JSON_ARRAY_SIZE} JMeter Variable

JSON Beanshell Variable

which can later be reused in If clause or an assertion.