我正在测试一个返回JSON响应的Web服务,我想从响应中提取多个值.典型的响应将在列表中包含多个值.例如:
{
"name":"@favorites",
"description":"Collection of my favorite places",
"list_id":4894636,
}
Run Code Online (Sandbox Code Playgroud)
响应将包含许多部分,如上例所示.
我想在Jmeter中做的是通过JSON响应并按照我可以将返回的名称和描述作为一个条目进行迭代的方式拉出上面概述的每个部分.
到目前为止我能够做的是使用模板$ 1 $返回带有正则表达式提取器("name":"(.+?)")的名称值.我想拉出名字和描述,但似乎无法让它发挥作用.我尝试使用正则表达式"name":"(.+?)","description":"(.+?)",模板为$ 1 $$ 2 $,但没有任何成功.
有谁知道在这个例子中我如何使用正则表达式来提取多个值?
使用BeanShell 脚本来处理 JSON 响应可能是值得的。
因此,如果您需要从响应中获取所有“名称/描述”对(对于每个部分),您可以执行以下操作:
1. 从循环中的响应中提取所有“名称/描述”对;
2. 以方便的格式将提取的对保存在 csv 文件中;
3. 稍后在代码中从 csv 文件读取保存的对 -在循环中使用CSV 数据集配置,例如
JSON 响应处理可以使用 BeanShell 脚本(~ java)+任何 json 处理库(例如json-rpc-1.0)来实现:
- 在BeanShell Sampler或BeanShell PostProcessor中;
- 目前默认的 jmeter 交付中提供了所有必需的 beanshell 库;
- 要使用 json 处理库,请将 jar 放入 JMETER_HOME/lib 文件夹中。
从原理上讲,它看起来像:
对于 BeanShell 后处理器:
线程组
。。。
您的 HTTP 请求
BeanShell PostProcessor // 作为子级添加
。。。
对于 BeanShell Sampler:
线程组
。。。
您的 HTTP 请求
BeanShell Sampler // 添加单独的采样器 - 在您之后
。。。
在这种情况下,使用哪一个没有区别。

您可以将代码本身放入采样器主体(“脚本”字段)或存储在外部文件中,如下所示。
采样器代码:
import java.io.*;
import java.util.*;
import org.json.*;
import org.apache.jmeter.samplers.SampleResult;
ArrayList nodeRefs = new ArrayList();
ArrayList fileNames = new ArrayList();
String extractedList = "extracted.csv";
StringBuilder contents = new StringBuilder();
try
{
if (ctx.getPreviousResult().getResponseDataAsString().equals("")) {
Failure = true;
FailureMessage = "ERROR: Response is EMPTY.";
throw new Exception("ERROR: Response is EMPTY.");
} else {
if ((ResponseCode != null) && (ResponseCode.equals("200") == true)) {
SampleResult result = ctx.getPreviousResult();
JSONObject response = new JSONObject(result.getResponseDataAsString());
FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir") + File.separator + extractedList);
if (response.has("items")) {
JSONArray items = response.getJSONArray("items");
if (items.length() != 0) {
for (int i = 0; i < items.length(); i++) {
String name = items.getJSONObject(i).getString("name");
String description = items.getJSONObject(i).getString("description");
int list_id = items.getJSONObject(i).getInt("list_id");
if (i != 0) {
contents.append("\n");
}
contents.append(name).append(",").append(description).append(",").append(list_id);
System.out.println("\t " + name + "\t\t" + description + "\t\t" + list_id);
}
}
}
byte [] buffer = contents.toString().getBytes();
fos.write(buffer);
fos.close();
} else {
Failure = true;
FailureMessage = "Failed to extract from JSON response.";
}
}
}
catch (Exception ex) {
IsSuccess = false;
log.error(ex.getMessage());
System.err.println(ex.getMessage());
}
catch (Throwable thex) {
System.err.println(thex.getMessage());
}
Run Code Online (Sandbox Code Playgroud)
还有一组关于此的链接:
更新。2017 年 8 月:
目前,JMeter 有一组内置组件(从第 3 方项目合并)来处理 JSON,无需编写脚本: