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);
5 Likes

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

Hi ,

I had a follow up question on this . My example response json is shown below
{
ā€œcam:testā€:ā€œ1970-01-01T00:00:00Zā€,
ā€œcam:test2ā€:ā€œ1970-01-01T00:00:00Zā€,
ā€œcam:test3ā€:ā€œ1970-01-01T00:00:00Zā€,
ā€œcam:test4ā€:1970
}

Could you please tell how do i retrieve the value when i have colon in the json field name

Hi @test.vtw welcome to the community :partying_face:

Please read the similar post discussed here.

You should be using the bracket notation instead of dot notation.

For example,

let response=pm.response.json();
console.log(response);
pm.environment.set("camtest1", response['cam:test']);
pm.environment.set("camtest2", response['cam:test2']);

This is just based on the response you have provided above, please edit the path if needed :blush: I hope this helps!

2 Likes

Hi @bpricilla can you please help me extract and save the value of ā€œidā€ inside ā€˜Bodyā€™ from below request
[

{

    "Id": 1,

    "StatusCode": 201,

    "Headers": {

        "Trace-Id": "af40c0f6-cae1-45b6-b925-08f03b95b6a5",

        "Content-Type": "application/hal+json; charset=utf-8",

        "Location": "/districts/b4668e48-1039-4822-91df-81883c3579f4/ag-club-affiliations/5802631a-06d9-4901-86b7-8525a34a84a5",

        "Content-Length": "1138"

    },

    "Body": {

        "message": "",

        "startDate": "2021-12-01",

        "endDate": "2022-06-30",

        **"id": "5802631a-06d9-4901-86b7-8525a34a84a5",**

        "_links": {

            "self": {

                "href": "/districts/b4668e48-1039-4822-91df-81883c3579f4/ag-club-affiliations/5802631a-06d9-4901-86b7-8525a34a84a5",

                "method": "GET|PATCH|DELETE"

            },

            "ag_club_affiliations": {

                "href": "/districts/b4668e48-1039-4822-91df-81883c3579f4/ag-club-affiliations",

                "method": "POST|PUT"

            },

            "individual": {

                "href": "/individuals/189d8777-5dab-408d-a759-5e4696d59df4",

                "method": "GET|PATCH"

            },

            "district": {

                "href": "/districts/b4668e48-1039-4822-91df-81883c3579f4",

                "method": "GET"

            },

            "club": {

                "href": "/clubs/1063969e-341a-40a4-9713-02a54c3079f4",

                "method": "GET|PATCH"

            }

        },

        "_embedded": {

            "organization": {

                "name": "Los Ejidos-Piura",

                "id": "1063969e-341a-40a4-9713-02a54c3079f4",

                "type": "Rotary_Club",

                "_links": {

                    "self": {

                        "href": "/clubs/1063969e-341a-40a4-9713-02a54c3079f4",

                        "method": "GET|PATCH"

                    }

                }

            },

            "individual": {

                "id": "189d8777-5dab-408d-a759-5e4696d59df4",

                "firstName": "cxDHYu",

                "lastName": "Au",

                "middleName": "yyblxb",

                "prefix": null,

                "suffix": null,

                "localizedName": null,

                "_links": {

                    "self": {

                        "href": "/individuals/189d8777-5dab-408d-a759-5e4696d59df4",

                        "method": "GET|PATCH"

                    }

                }

            }

        }

    }

},

{

    "Id": 2,

    "StatusCode": 201,

    "Headers": {

        "Trace-Id": "af40c0f6-cae1-45b6-b925-08f03b95b6a5",

        "Content-Type": "application/hal+json; charset=utf-8",

        "Location": "/districts/911ee7b9-197f-4ac5-b752-5e803e3a79f4/ag-club-affiliations/4ad8d5e4-9828-436b-b35a-9c3ad24a84a5",

        "Content-Length": "1140"

    },

    "Body": {

        "message": "",

        "startDate": "2021-12-01",

        "endDate": "2022-06-30",

        "id": "4ad8d5e4-9828-436b-b35a-9c3ad24a84a5",

        "_links": {

            "self": {

                "href": "/districts/911ee7b9-197f-4ac5-b752-5e803e3a79f4/ag-club-affiliations/4ad8d5e4-9828-436b-b35a-9c3ad24a84a5",

                "method": "GET|PATCH|DELETE"

            },

            "ag_club_affiliations": {

                "href": "/districts/911ee7b9-197f-4ac5-b752-5e803e3a79f4/ag-club-affiliations",

                "method": "POST|PUT"

            },

            "individual": {

                "href": "/individuals/aeefcad1-ef32-4d4b-8ade-17e25d64acf4",

                "method": "GET|PATCH"

            },

            "district": {

                "href": "/districts/911ee7b9-197f-4ac5-b752-5e803e3a79f4",

                "method": "GET"

            },

            "club": {

                "href": "/clubs/13e87aad-592b-43fc-86f1-5e2c696279f4",

                "method": "GET|PATCH"

            }

        },

        "_embedded": {

            "organization": {

                "name": "Malikipuram",

                "id": "13e87aad-592b-43fc-86f1-5e2c696279f4",

                "type": "Rotary_Club",

                "_links": {

                    "self": {

                        "href": "/clubs/13e87aad-592b-43fc-86f1-5e2c696279f4",

                        "method": "GET|PATCH"

                    }

                }

            },

            "individual": {

                "id": "aeefcad1-ef32-4d4b-8ade-17e25d64acf4",

                "firstName": "IvWI",

                "lastName": "pWrH",

                "middleName": "AuDmGTy",

                "prefix": null,

                "suffix": null,

                "localizedName": "Nagendra",

                "_links": {

                    "self": {

                        "href": "/individuals/aeefcad1-ef32-4d4b-8ade-17e25d64acf4",

                        "method": "GET|PATCH"

                    }

                }

            }

        }

    }

},
1 Like

hey @DIS_Automation ~would you try this code?
let response=pm.response.json();
console.log(response);
pm.environment.set(ā€œidā€,response.Body.id);

Or there are might be a geeky long way to get it :face_with_hand_over_mouth:

const response = JSON.parse(Buffer.from(Array.from(pm.response.stream)).toString('UTF-8'))

before I learned pm.response.json() :smiley:

Very new to Postman,
Iā€™m trying to extract certain data from the response body and then use that data to send a post request this is where Iā€™m at:

const response = pm.response.json();
const toolLtp = response.map(tool => tool.ltp)
console.log(toolLtp)

This is what my body is

{"status":"200","level":null,"message":"Success","data":{"ltp":1985.0,"Open":2000,"High":2110,"Low":1950}}

@Craigs

You donā€™t need to use map to get to the element you want.

let body = {
    "status":"200",
    "level":null,
    "message":"Success",
    "data":
    {
        "ltp":1985.0,
        "Open":2000,
        "High":2110,
        "Low":1950
    }
};


console.log(body.data.ltp); // 1985
1 Like

Thanks,
The ltp, Open, High and low in the body here changes frequently it is not a fixed value so i need to send a get request and only extract the ltp from the body, how do i do that.

@Craigs

Iā€™m assuming you mean the value changes frequently, but the ā€œltpā€ key should always appear?

As long as the key stays the same, then the example I provided should work.

console.log(body.data.ltp); // 1985

Yes, the value of LTP changes frequently so this is what Iā€™m doing:
const response = pm.response.json();
let body = {
ā€œstatusā€:ā€œ200ā€,
ā€œlevelā€:null,
ā€œmessageā€:ā€œSuccessā€,
ā€œdataā€:
{
ā€œltpā€:1985.0,
ā€œOpenā€:2000,
ā€œHighā€:2110,
ā€œLowā€:1950
}
};
console.log(body.data.ltp); // 1985
so when i send a get request the value of ltp now has changed to 1990 but i still get 1985 i want to be able to get 1990 instead of 1985.

Thanks once again for helping me out here

@Craigs

The ā€œlet body =ā€ was just an example response I set for testing purposes.

Instead of parsing the response as I obviously donā€™t have access to your API. I just set a variable with the same format as the example body you provided.

Itā€™s always going to return the figures that I hardcoded into the variable.

You would change this to the variable that you stored the parsed response.

const response = pm.response.json();
console.log(response.data.ltp);

If you are new to Postman. I would recommend going through the Postman training if you havenā€™t done so yet.

Postman Galaxy Training | Postman API Network

Run through the ā€œAPIs 101 Trainingā€, then the ā€œTesting and Automation Trainingā€ course.

Hi Everyone,

This is really useful, thank you for the contribution. I am dealing with a similar issue. I am trying to extract more than 1 value of the response and store them in different variables. (Ex: IP addresses). The test works if both values are the same(ex: enabled) but if I try with the IP it gives me the error ā€œCouldnā€™t evaluate the test script:
ReferenceError: address is not definedā€
Any idea of how could achieve that?

Hey @andrezmolina247 :wave:

Welcome to the Postman Community! :postman:

Whatā€™s the full response body look like (mainly interested in the start of it)?

Is objects a actual property of the response or something that you have just added to the reference?

Does responseData[0]["ipv4-address"] work for you?

The one that you sent me doesn not work. If I do
pm.collectionVariables.set(ā€œIPā€, responseData.objects[0].enabled) it works

below the full response

{
    "objects": [
        {
            "comments": "",
            "enabled": true,
            "ipv4-address": "172.16.164.104",
            "ipv4-mask-length": "23",
            "ipv6-address": "Not-Configured",
            "ipv6-autoconfig": "Not configured",
            "ipv6-local-link-address": "Not Configured",
            "ipv6-mask-length": "Not-Configured",
            "name": "eth0",
            "type": "physical"
        },
        {
            "comments": "",
            "enabled": true,
            "ipv4-address": "7.7.7.2",
            "ipv4-mask-length": "30",
            "ipv6-address": "Not-Configured",
            "ipv6-autoconfig": "Not configured",
            "ipv6-local-link-address": "Not Configured",
            "ipv6-mask-length": "Not-Configured",
            "name": "eth1",
            "type": "physical"
        },
        {
            "comments": "",
            "enabled": true,
            "ipv4-address": "192.168.80.253",
            "ipv4-mask-length": "24",
            "ipv6-address": "Not-Configured",
            "ipv6-autoconfig": "Not configured",
            "ipv6-local-link-address": "Not Configured",
            "ipv6-mask-length": "Not-Configured",
            "name": "eth2",
            "type": "physical"
        },
        {
            "comments": "",
            "enabled": true,
            "ipv4-address": "127.0.0.1",
            "ipv4-mask-length": "8",
            "ipv6-address": "Not-Configured",
            "ipv6-autoconfig": "Not configured",
            "ipv6-local-link-address": "Not Configured",
            "ipv6-mask-length": "Not-Configured",
            "name": "lo",
            "type": "loopback"
        }
    ]
}

I just confirmed that the issue is related to the ā€œ-ā€ character. If i try to do the same the with the value ā€œnameā€ where are different results it works. Still donā€™t know how to avoid that issue of the ā€œ-ā€

That makes sense, itā€™s the reason I added [0]["ipv4-address"] in my response.

Certain characters used as property keys like numbers, : or - etc will break the chained reference to the property. They would need to be referenced using bracket notation and not dot notation.

A post was split to a new topic: Comparing responses