Sharing tips and tricks with others in the Postman community

Extracting values from a JSON response

I notice lots of questions from the community which all have a similar flavour - Users are having trouble extracting data from a JSON response body when the value is within an array.

These are normally JavaScript related questions, more than specific Postman questions but I want to use this thread to offer more support around this problem.

For these examples I’ll be using the https://randomuser.me API, this returns lots of random user data, in a JSON format. This is perfect to help with explaining ways to extract data.

This is an example of the response body returned from the randomuser API:

{
    "results": [
        {
            "gender": "female",
            "name": {
                "title": "mrs",
                "first": "tilla",
                "last": "sævareid"
            },
            "location": {
                "street": "mogens thorsens gate 3652",
                "city": "alta",
                "state": "nordland",
                "postcode": "1152",
                "coordinates": {
                    "latitude": "49.9350",
                    "longitude": "113.7576"
                },
                "timezone": {
                    "offset": "-6:00",
                    "description": "Central Time (US & Canada), Mexico City"
                }
            },
            "email": "tilla.sæ[email protected]",
            "login": {
                "uuid": "ed63d908-5b6f-4cf5-9abe-0be5107000ed",
                "username": "tinybird773",
                "password": "planet",
                "salt": "Tx7V7veO",
                "md5": "c601d954f8144194fd1f2df8e4d8e05e",
                "sha1": "205292c0af997e9c95ae8bd1247a8962a2240eac",
                "sha256": "ddcf7358dda748e1c61c8ea09434e5d3fd7b5aedf90a922c44423fb48815ff09"
            },
            "dob": {
                "date": "1991-12-12T09:06:33Z",
                "age": 27
            },
            "registered": {
                "date": "2007-10-10T12:43:45Z",
                "age": 11
            },
            "phone": "24000987",
            "cell": "94325402",
            "id": {
                "name": "FN",
                "value": "12129107373"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/8.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/8.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/8.jpg"
            },
            "nat": "NO"
        }
    ],
    "info": {
        "seed": "dab43d72e88a90df",
        "results": 1,
        "page": 1,
        "version": "1.2"
    }
} 

I’m going to do some basic global variable setting using the JSON response to demonstrate how to extract the values. You could also use this method to set the environment variables too.

Generally, users run into problems when the response body contains an array and this is when people tend to reach out for support because the code that would have been used the get the data from a single object, no longer works.

let jsonData = pm.response.json()

pm.globals.set('gender', jsonData.results.gender)

As you can see from the image, it’s created the global variable called gender but it’s failed to extract the value from the response.

As the results property type is an array with a list of objects within it, we need to specify which object we would like to use.

This response only has a single item and to get the data from within this object we reference it using [0]. Arrays are zero indexed so they start from 0 rather than 1 - This is an important thing to remember when working with JS arrays.

let jsonData = pm.response.json()

pm.globals.set('gender', jsonData.results[0].gender)

This time because we have added [0] to results, it has set the gender variable correctly. What that’s basically doing is saying that we want to get the value from the "gender" key, in the first object of the array.


Hardcoding the array index number is going to be ok if you know that you only have a single object but if you have multiple objects, you would need to iterate through those objects to get each of the values.

This time we’re going to add some JavaScript code to loop through the results array and get all the values from the "first" key, within the "name" object. Don’t worry, this will all make sense with a few examples.

Within the Postman application, there are a few built-in modules that we can use to help us out. For this example, I’m going to use the _.each() function from the Lodash module.

Using this function we can loop through the results array and grab each of the values we require, without the need to hardcode the index number.

let jsonData = pm.response.json()

_.each(jsonData.results, (result) => {
    pm.globals.set('firstName', result.name.first)
})

You can see in the image that we have extracted the "first" value and set this as the firstName global variable.

There’s a slight problem with this approach if there is more than 1 object. As we loop through the array, the variable is set but as there is more than 1 that value is overwritten with the last one. Not an ideal situation but we can add a couple of lines to our code to collect each of the first names, in the array.

This time we have created an empty array and assigned this to the firstNames variable. Next, within the loop, we are collecting each of the first names and using the .push() method to add these to the firstNames array.

Finally, when the loop has finished, we set a new firstNames global variable and use JSON.stringify() to save the array values as a string.

let jsonData   = pm.response.json()
let firstNames = []

_.each(jsonData.results, (result) => {
    firstNames.push(result.name.first)
})

pm.globals.set('firstNames', JSON.stringify(firstNames)) 

Now we can see that 5 different names have been set in the firstNames variable.


Just as a quick example - I’ll add a Test using a loop so we can see how this can be used to check for a certain value.

The API has a number of filters, one of which is to return a specific gender, we’re also returning 100 results and that would take a while to check each one manually so we can create a Test to do this for us in super quick time.

GET https://randomuser.me/api/?results=100&gender=female

let jsonData = pm.response.json()

pm.test('The `female` filter returns the correct gender', () => {
    _.each(jsonData.results, (result) => {
        pm.expect(result.gender).to.equal('female')
    })
})


So this was a basic walkthrough of how to extract data from a response body which has an array of objects. There are a number of different ways that we could do this using some of the different Lodash functions but for now, I’ve just kept it simple.

If this doesn’t make sense or you need to achieve something different, please reach out to me. :slight_smile:

13 Likes