[英]How to get Key and Value from JSON object in Javascript(Postman)
[英]Postman - How to get a value from a JSON array inside a JSON object
我是 JSON 和 Postman 的新手。 我想我正在尝试做一些非常简单的事情。
我创建了一个 POST 请求,它将获得如下所示的 JSON 响应。
在下面来自FieldGroups
数组内部的示例中,我想获取Id
的值,但FieldGroups
是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
}
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);
}
});
}
我希望我能帮上忙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.