簡體   English   中英

Postman - 如何從 JSON 對象內的 JSON 數組中獲取值

[英]Postman - How to get a value from a JSON array inside a JSON object

我是 JSON 和 Postman 的新手。 我想我正在嘗試做一些非常簡單的事情。

我創建了一個 POST 請求,它將獲得如下所示的 JSON 響應。

在下面來自FieldGroups數組內部的示例中,我想獲取Id的值,但FieldGroupsName值為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM