简体   繁体   中英

how to calculate length of JSON array using JMeter?

I am using Jmeter to make an API call. The response is:

{
  "qid": [
    {
      "id": "88e4b027b72f793d3c",
      "created": 1410955125065
    },
    {
      "id": "54197788e4",
      "created": 1410955125065
    },
    {
      "id": "788e4",
      "created": 1410955125065
    },
    {
      "id": "5419778",
      "created": 1410955125065
    },
    ....
  ]
}

The length of the JSON array varies for different API requests. How do I determine the length of the JSON array?

JMeter has Beanshell post processors.

So import Java JSON parser.

import org.json.*;
JSONObject jsonObj = new JSONObject(prev.getResponseDataAsString());
JSONArray jsonQid = jsonObj.getJSONArray("qid");
//jsonQid.length  --> should print the array length

A more simple approach is to use the "Content-Length" header parameter.

Remember that this value stands for the actual body length, after compression, if any.

String response = prev.getResponseDataAsString();
JSONParser parser = new JSONParser();
JSONArray arrayJson = (JSONArray) parser.parse(response);
String size = arrayJson.size().toString();

I found using the JSON Path Postprocessor even easier with the latest version of JMeter. In your example, add the following JSON path expression: $.qid.*.id.

Add a debug sampler with a listener to your script. After the script is run, the variable qid_matchNr will be equal to the size of the JSON array you are interested in. That variable will be available to use with your script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM