在 beanshell 脚本中提取 json 个值
Extract json values in beanshell script
这是我的 json 我想使用 beanshell 提取名字和代码 script.But 我无法提取值。
请帮忙
{
"code":"HNYC",
"message":"Sucess",
"data":{
"Employeid":"TGRDH-887",
"Perosonal":{
"Details":{
"firstname":"Sam",
"id":3566,
"dob":"23/11/1990",
"Yearofjoing":"2018",
"Salary":30000,
"Address":"New Delhi",
"City":"Delhi"
}
}
}
}
豆壳代码:
import com.eclipsesource.json.JsonObject;
String jsonString = prev.getResponseDataAsString();
JsonObject accountId = JsonObject.readFrom(jsonString);
String code = accountId.getJSONObject("code");
print("value "+code);
您可以直接从 JSONObject 获取 code
值,因为它在 JSONObject refer
中是 属性
String code = accountId.get("code");
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject getData = jsonObject.getJSONObject("data");
JSONObject getPerosonal = getData.getJSONObject("Perosonal");
JSONObject getDetails = getPerosonal.getJSONObject("Details");
Object firstname= getDetails.get("firstname");
System.out.println(firstname);
首先,您知道 JSON Extractor? If not - consider using it as it provides possibility to fetch JSON data using simple JSONPath 查询,例如 $..code
和 $.. firstname
如果您仍想编写脚本,请注意 since JMeter 3.1 it is recommended to use Groovy for any form of scripting. Groovy is more "modern" language than Beanshell, it supports all new Java features and it has a lot of enhancements 在 Java SDK
之上
其中一个通过 JsonSlurper class 内置 JSON 支持,因此您可以将代码缩短为:
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
String code = json.code
log.info(code)
演示:
更多信息:
这是我的 json 我想使用 beanshell 提取名字和代码 script.But 我无法提取值。 请帮忙
{
"code":"HNYC",
"message":"Sucess",
"data":{
"Employeid":"TGRDH-887",
"Perosonal":{
"Details":{
"firstname":"Sam",
"id":3566,
"dob":"23/11/1990",
"Yearofjoing":"2018",
"Salary":30000,
"Address":"New Delhi",
"City":"Delhi"
}
}
}
}
豆壳代码:
import com.eclipsesource.json.JsonObject;
String jsonString = prev.getResponseDataAsString();
JsonObject accountId = JsonObject.readFrom(jsonString);
String code = accountId.getJSONObject("code");
print("value "+code);
您可以直接从 JSONObject 获取 code
值,因为它在 JSONObject refer
String code = accountId.get("code");
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject getData = jsonObject.getJSONObject("data");
JSONObject getPerosonal = getData.getJSONObject("Perosonal");
JSONObject getDetails = getPerosonal.getJSONObject("Details");
Object firstname= getDetails.get("firstname");
System.out.println(firstname);
首先,您知道 JSON Extractor? If not - consider using it as it provides possibility to fetch JSON data using simple JSONPath 查询,例如 $..code
和 $.. firstname
如果您仍想编写脚本,请注意 since JMeter 3.1 it is recommended to use Groovy for any form of scripting. Groovy is more "modern" language than Beanshell, it supports all new Java features and it has a lot of enhancements 在 Java SDK
之上其中一个通过 JsonSlurper class 内置 JSON 支持,因此您可以将代码缩短为:
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
String code = json.code
log.info(code)
演示:
更多信息: