在 JMETER 中循环遍历 JSON 响应 + [英] Looping through JSON response + in JMETER

查看:26
本文介绍了在 JMETER 中循环遍历 JSON 响应 +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jmeter 进行性能测试并停留在以下几点:我收到来自 Webapi 的 JSON 响应,如下所示:

PersonInfoList:人[0]{编号:1姓名:史蒂夫}[1]人{编号:2姓名:马克}

我需要根据这个 JSON 数组的计数来获取 id 并创建一个逗号分隔的字符串作为 ("Expected value" = 1,2)

我知道如何使用 JSON 后处理器或正则表达式处理器读取特定元素,但无法遍历数组并按照说明创建字符串,以便我可以在下一个采样器请求中使用该值.

请帮我解决这个问题:我正在使用 Jmeter 3.0,如果这可以在不使用外部第三方库的情况下实现,那就太好了.抱歉上面的 JSON 语法

解决方案

实际上类似的功能来自

I am using Jmeter for performance testing and stuck at following point: I am getting a JSON response from Webapi as follows:

PersonInfoList:
Person
[0]
{
  id: 1
  name: Steve
}
[1]
Person
{
  id: 2
  name: Mark
}

I need to get the ids based on the count of this JSON array and create a comma separated string as ("Expected value" = 1,2)

I know how to read a particular element using JSON Post processor or Regex processor but am unable to loop through the array and create a string as explained so that I can use this value in my next sampler request.

Please help me out with this: I am using Jmeter 3.0 and if this could be achieved without using external third party libs that would be great. Sorry for the JSON syntax above

解决方案

Actually similar functionality comes with JSON Path PostProcessor which appeared in JMeter 3.0. In order to get all the values in a single variable configure JSON Path PostProcessor as follows:

  • Variable Names: anything meaningful, i.e. id
  • JSON Path Expressions: $..id or whatever you use to extract the ids
  • Match Numbers: -1
  • Compute concatenation var (suffix _ALL): check

As a result you'll get id_ALL variable which will contain all JSON Path expression matches (comma-separated)

More "universal" answer which will be applicable for any other extractor types and in fact will allow to concatenate any arbitrary JMeter Variables is using scripting (besides if you need this "expected value and parentheses)

In order to concatenate all variables which names start with "id" into a single string add Beanshell PostProcessor somewhere after JSON Path PostProcessor and put the following code into "Script" area

StringBuilder result = new StringBuilder();
result.append("("Expected value" = ");
Iterator iterator = vars.getIterator();

while (iterator.hasNext()) {
  Map.Entry e = (Map.Entry) iterator.next();
  if (e.getKey().matches("id_(\d+)")) {
      result.append(e.getValue());
      result.append(",");
  }
}
result.append(")");
vars.put("expected_value", result.toString());

Above code will store the resulting string into ${expected value} JMeter Variable. See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information regarding bypassing JMeter limitations using scripting and using JMeter and Java API from Beanshell test elements.

Demo:

这篇关于在 JMETER 中循环遍历 JSON 响应 +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆