Postman - How to count occurrences of a specific object in a JSON response

徘徊边缘 提交于 2019-12-06 05:24:11

It is a rather specific solution but I hope it helps. The description is added as comments:

// Convert the response body to a JSON object
var jsonData = pm.response.json()

// Create a count variable which will be increased by 1 everytime IsArchived occurs
var count = 0;

function countIsArchived() {
    // Loop through the FieldGroupsArray
    _.each(jsonData.FieldGroups, (fieldGroupsArray) => {
        // Loop through the FieldDefinitionsArray
        _.each(fieldGroupsArray.FieldDefinitions, (fieldDefinitionsArray) => {
            // Check if IsArchived exists
            if(fieldDefinitionsArray.IsArchived) {
                // Increase count by 1
                count++;
            }
        });
    });

    // IF you want it:
    // Check if IsArchived exists on the top level of the JSON response and increase count
    if(jsonData.IsArchived) {
        count++;
    }
    // IF you want it:
    // Create a Postman environment variable and assign the value of count to it
    pm.environment.set("count", count);
}

Additional info:

The , after the following object is not needed. It invalidates the JSON:

{
    "Id": 33,
    "DisplayName": "Long Description",
    "IsArchived": false
},  <--
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!