Extract value from a JSON Response Body via the Test Scripts

I’m attempting to use a test script to store part of the response in an environment variable. Here’s the response that I’m attempting to parse:

{
    "meta": {
        "query_time": 1.61e-7,
        "trace_id": "bfa4ee6d-b15d-4920-8f9f-1a90bcb1b0b4"
    },
    "errors": [],
    "resources": [
        {
            "id": "xxxxxx",
            "group_type": "static",
            "name": "xxxxxx",
            "description": "xxxxxx",
            "assignment_rule": "xxxxx",
            "created_by": "xxxxx",
            "created_timestamp": "xxxxx",
            "modified_by": "xxxxx",
            "modified_timestamp": "xxxx"
        }
    ]
}

Here’s my test script code:

let responseData=pm.response.json();
console.log(responseData);
pm.environment.set("HostsToRemove", responseData.resources.name);

This fails with an error of “TypeError: Cannot read property of ‘name’ of undefined”. It appears to be because, under resources, there’s a set of brackets that seems to add another level to the JSON response. If i switch to responseData.meta.query_time then my code works perfectly. I just can’t figure out how to modify the response data values to get down 1 more level so I can reference the ‘name’ field. Any ideas?

Hey @jgreene7930,

Welcome to the community! :star:

Looking at your example response data - I can see that resources is an array which contains an object.

You would need to use resources[0].name to access the first object in the array.

You were on the right lines with logging the response to the Postman Console. This is what it would have logged:

Screenshot 2020-04-09 at 09.27.10

This is showing you that resources is an array with 1 object and if you were to expand this, you will see that the objects are zero-indexed. The first object would be 0 and that’s the reference that’s been added above [0].

So the full statement to set the variable would be:

let responseData = pm.response.json();
pm.environment.set("HostsToRemove", responseData.resources[0].name);

Thank you! That makes total sense. I appreciate your help here.