Guide on Postman: Tracking the number of occurrences for a particular object in a JSON reply

I am just starting out with JSON and Postman. I have a simple task in mind.

I have set up a GET request that will return a JSON response like the one below.

In this example, I want to extract the count of all "IsArchived" attributes in the response.

The number of these attributes can vary in each response.

Any suggestions on how I can achieve this? Thank you in advance.

{
    "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",
                    "IsArchived": false
                },
                {
                    "Id": 2,
                    "DisplayName": "Short Description",
                    "IsArchived": false
                },
                {
                    "Id": 33,
                    "DisplayName": "Long Description",
                    "IsArchived": false
                },
            ]
        },
        {
            "Id": "5ed8746b-0fa8-4022-8216-ad3af17db91f",
            "Name": "Somethingelse",
            "FieldDefinitions": [
                {
                    "Id": 123,
                     "DisplayName": "Attribution",
                    "IsArchived": false
                },
                {
                    "Id": 1584,
                    "DisplayName": "FC1",
                    "IsArchived": false
                },
                {
                    "Id": 623,
                    "DisplayName": "Sizes",
                    "IsArchived": false,
                    "Owner": {
                        "Id": 208,
                        "Name": "The Boss"
                    },
                    "Unit": "",
                    "Options": [
                        {
                            "Id": 1,
                            "Value": "XS"
                        },
                        {
                            "Id": 2,
                            "Value": "S"
                        },
                        {
                            "Id": 3,
                            "Value": "M"
                        }
                    ]
                }
             ]
        }
    ],
    "IsArchived": false
    "Version": 1
}

Answer №1

This solution is quite specific, but I believe it can be helpful. The comments provide a description of the code:

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

// Initializing a count variable to track occurrences of IsArchived
var count = 0;

function countIsArchived() {
    // Iterating through the FieldGroupsArray
    _.each(jsonData.FieldGroups, (fieldGroupsArray) => {
        // Iterating through the FieldDefinitionsArray
        _.each(fieldGroupsArray.FieldDefinitions, (fieldDefinitionsArray) => {
            // Checking for the presence of IsArchived
            if(fieldDefinitionsArray.IsArchived) {
                // Incrementing the count
                count++;
            }
        });
    });

    // Optional:
    // Checking for IsArchived at the top level of the JSON response and incrementing count
    if(jsonData.IsArchived) {
        count++;
    }
    // Optional:
    // Creating a Postman environment variable and storing the count value
    pm.environment.set("count", count);
}

Extra information:

The , following the specified object should be removed as it disrupts the JSON validity:

{
    "Id": 33,
    "DisplayName": "Long Description",
    "IsArchived": false
},  <--

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain module-specific members through programmatic means

When working on a browser, the code may appear like this: //retrieve all enumerable properties of `this` function globalMems() { var g = this; var ret = {}; for (var prop in g) { ret[prop] = g[prop]; } return ret; } In Node.js, this does ...

Adding flair to the encompassing container

Below is the HTML code that I am working with: <div class="um-field field-date"> <p class="form-row " id="date_field"> <label class="date"> <input data-label="Date" data-value="" type="date" class="input-date um-frontend-f ...

React Redux - There is an error during rendering as expected props have not been received yet

After retrieving data from an API and storing it in the Redux state, I utilize a helper function within mapStateToProps to filter and modify a portion of that data before passing it along as props. Although everything appears to be functioning correctly b ...

Struggling to Upload a Json Array into Mongodb

How can I successfully import a jsonArray into a mongoDB using the Windows command prompt? The command I'm attempting to use is as follows: C:\mongo>mongoimport --jsonArray -d testdb -c testcollection -f my_test_file.json I have verified th ...

How can one leverage Node JS to effectively manage events?

Is it considered a best practice to utilize events for communication between functions within ExpressJS? If so, what is the proper way to send arguments along with my emit event? ...

Select one href by clicking and apply addClass

I have a one-page HTML document with links in the header. I want to make it so that when I click on a link (<a>), only that specific link changes its class to (.links). I've tried various methods, but the current jQuery method I'm using ad ...

How to Utilize JQuery for Sticky Elements

I am experimenting with a unique twist on the classic Sticky Element concept. Check out for a typical sticky element example. Instead of the traditional sticky behavior, I am looking to have an element initially anchored to the bottom of the user's ...

The validation feature is ineffective when used with Material UI's text input component

I need a function that can validate input to make sure it is a number between 1 and 24. It should allow empty values, but not characters or special symbols. function handleNumberInput(e) { const re = /^[0-9\b]+$/; const isNumber = re.test(e.target.val ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...

Exploring the combination of Holder.js and Rails routes

What's the best way to integrate Holder.js into my Rails application? I'm running into issues where Rails is interpreting the parameters passed to the script as routes and returning 404 errors. Has anyone successfully implemented this before? ...

What are some ways to conceal the API connection within a button?

I have a code that allows me to perform a certain API call with a link. Here is an example: <a class="btn btn-default" href="https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey='.$user.'&Password='.$pass.'&Domain=&ap ...

Extract data from JSON and present it in a tabular format

Below is the JSON data that I need to parse { "kickers": [ { "_id": "iLntVcAmPn", "nflPlayerName": "Stephen Gostkowski", "nflPlayerNumber": 3, "nflPlayerPosition": "K", "nflPlayerTeam": "ne", "nflPlayerCardType": ...

Dynamically adjusting the width of an HTML element with ng-style using percentage values in AngularJS

I am facing a challenge where I need to display a progress bar in my UI based on a percentage value stored in a JSON response object. Here is an example of the JSON object: { completionPercent: 42 } The desired UI outcome should look like this: ┌ ...

Manage image placement using CSS object-position

I have the following code snippet: img{ width: 100%; height: 1000px; object-fit: cover; object-position: left; } <!DOCTYPE html> <html lang="en"> <head> <meta charset ...

Issues encountered with AngularJS directive binding inner content not functioning as expected

I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm try ...

Utilize the Postgres json_object feature to include a json field only when the value is not null

When utilizing the jsob_build_object function to create JSON from data within a table, I encountered an issue. select json_build_object('name', p.name, 'birthday', p.birthday) FROM Person p limit 2 The output is: {"name":"John", "bir ...

Choose an image and save the selection information for the following page (Tarot card)

I'm in the process of creating a website that showcases multiple tarot cards. The goal is for users to select the cards they're interested in and have their chosen card displayed on the next page. I've implemented some code for selecting the ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Exploring the possibilities of using the typeof operator within an Event

I want to log some information if the input value is a number. However, I am facing an issue where it's not working and no bugs are appearing. Here is a snippet of code from CodePen (https://codepen.io/matoung/pen/KBNmPP) let button = document.que ...

Retrieving Data using Map in ReactJS

I'm in the process of creating a web app and I have an array of data with URLs in each element. I'm struggling to figure out how to fetch data from these mapped URLs. useEffect(() => { axios .get(`someurl`) .then((response) =& ...