json 从 Postman 中的对象数组中提取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42257293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract value from array of objects in Postman
提问by xUrko
I want to extract Id value from the array with objects in Postman and then set it as an environment variable. In case JSON response is an object, the following script works, but not with an array of objects (my array has only one object).
我想从带有 Postman 对象的数组中提取 Id 值,然后将其设置为环境变量。如果 JSON 响应是一个对象,则以下脚本有效,但不适用于对象数组(我的数组只有一个对象)。
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data.Id);
JSON response:
JSON 响应:
[
{
"Id": 1287,
"LastName": "Trump",
"FirstName": "Donald",
"MiddleName": "Von",
"City": "New York City",
"Phone": "66 77 88",
"State": "New York",
"Fax": "111-222-333",
"ReferenceId": "12345",
"Active": false,
"CurrentWorkingSchemeId": null
}
]
回答by Always Sunny
If it is an array of objects, then just select the first object using index [0] before grabbing the object's key like this:
如果它是一个对象数组,那么在抓取对象的键之前,只需使用索引 [0] 选择第一个对象,如下所示:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data[0].Id);
回答by Sobhit Sharma
This works like charm! Basically what i am doing here is, parse the response and from the data array, take id and save it in postman environment variable.
这就像魅力一样!基本上我在这里做的是,解析响应并从数据数组中获取 id 并将其保存在邮递员环境变量中。
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++) `
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}

