我是JSON和Postman的新手。我想我正在尝试做一些非常简单的事情。
我创建了一个POST请求,该请求将获得如下所示的JSON响应。
在下面的示例中,我从FieldGroups
数组的内部获取值Id
,但前提是Name
的值为General
我该怎么办? 预先感谢。
{
"Id": 1328,
"Name": "AAA Test",
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"FieldGroups": [
{
"Id": "c81376f0-6ac3-4028-8d61-76a0f815dbf8",
"Name": "General",
"FieldDefinitions": [
{
"Id": 1,
"DisplayName": "Product Name"
},
{
"Id": 2,
"DisplayName": "Short Description"
},
{
"Id": 33,
"DisplayName": "Long Description"
},
]
},
{
"Id": "5ed8746b-0fa8-4022-8216-ad3af17db91f",
"Name": "Somethingelse",
"FieldDefinitions": [
{
"Id": 123,
"DisplayName": "Attribution"
},
{
"Id": 1584,
"DisplayName": "FC1"
},
{
"Id": 623,
"DisplayName": "Sizes",
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"Unit": "",
"Options": [
{
"Id": 1,
"Value": "XS"
},
{
"Id": 2,
"Value": "S"
},
{
"Id": 3,
"Value": "M"
},
]
}
]
}
],
},
"Version": 1
}
答案 0 :(得分:0)
Postman内置支持名为Lodash(代码中的_)的JavaScript实用程序库,您可以使用其功能以更简洁的方式遍历JSON数组。
由于我不确定您要实现的目标,因此请尝试使以下代码适应您的问题。
// Convert the response body to a JSON object
var jsonData = pm.response.json()
// Create a variable to which you will assign the value of Id later on
var generalId;
function setGeneralID() {
_.each(jsonData.FieldGroups, (arrayItem) => {
if(arrayItem.Name === 'General') {
// Assign the value of Id to the generalId variable
generalId = arrayItem.Id;
// OR (depending on what you want to do)
// Create a Postman environment variable and assign the value of Id to it
pm.environment.set("Id", arrayItem.Id);
}
});
}
希望我能帮上忙。