【发布时间】:2019-08-26 20:40:52
【问题描述】:
我正在尝试根据响应中的特定值设置邮递员环境变量。
我不确定用于获取价值的代码。
我知道我需要将响应设置为变量,如下所示:
var response = JSON.parse(responseBody);
而且我知道我可以使用以下内容来设置我的环境变量:
postman.setEnvironmentVariable("category_ref",myVariableName);
以下是我的回复中的一个 sn-p:
{
"id": 45,
"name": "Accommodation",
"description": ""
},
{
"id": 46,
"name": "Accommodation (Engineering)",
"description": ""
},
我想根据我已经知道的“名称”值获取“id”值。
举个例子,我希望我的代码给我一个 ID,其中 "name" = "Accommodation"
编辑:
根据以下答案更改为原始问题。
我的测试代码现在如下所示:
//Ensure the API Test Category is present
var response = JSON.parse(responseBody);
tests["my test"] = responseBody.has("Accommodation");
//pass in id into variable for delete step
var requiredId = pm.response.json().find(function(element){
if (element.name == "Accommodation"){
return element.id;
}
});
stringId = JSON.stringify(requiredId);
pm.environment.set("category_ref",stringId);
console.log("my string "+stringId);
我到控制台的输出如下所示,这也是发送到 category_ref 环境变量的值:
my string {"id":45,"name":"Accommodation","description":""}
剩下的问题是我不想像上面那样返回所有元素,我只想返回“45”,这是 name = 住宿的 id 值。
【问题讨论】:
标签: javascript json postman