简体   繁体   English

如何使用JMeter计算JSON数组的长度?

[英]how to calculate length of JSON array using JMeter?

I am using Jmeter to make an API call. 我正在使用Jmeter进行API调用。 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. JSON数组的长度因不同的API请求而异。 How do I determine the length of the JSON array? 如何确定JSON数组的长度?

JMeter has Beanshell post processors. JMeter具有Beanshell后处理器。

So import Java JSON parser. 因此,导入Java JSON解析器。

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. 一种更简单的方法是使用“ Content-Length”标头参数。

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. 我发现在最新版本的JMeter中使用JSON Path Postprocessor更加容易。 In your example, add the following JSON path expression: $.qid.*.id. 在您的示例中,添加以下JSON路径表达式:$ .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. 运行脚本后,变量qid_matchNr将等于您感兴趣的JSON数组的大小。该变量将可用于您的脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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