0

I have a GET request which returns an array of bodies:

[
    {
        "id": "79ad1daf-54f0-49cf-8628-7fb38457fdd1",
        "deviceId": "wowSomeRandomName",
        "deviceName": "wowSomeRandomName",
        "iconUrl": "/i/devicepics/smart_tv.svg",
        "lastUse": "2018-12-13T10:05:00.609Z"
    }
]

And I need to set these variables as global variables. I understand how to do that for external bodies outside of an array:

pm.environment.set("deviceUUID", pm.response.json().id);
pm.environment.set("deviceId", pm.response.json().deviceId);
pm.environment.set(. . . .);
and etc.

But what to do when they are inside of [ ]?

0

1 Answer 1

2

I think you can first convert the response to JSON then operate on that:

var responseData = JSON.parse(response);
pm.environment.set("deviceUUID", responseData[0].id);
pm.environment.set("deviceId", responseData[0].deviceId);
and etc

got this idea from: https://learning.getpostman.com/docs/postman/scripts/test_examples/

please let me know if this doesn't work.

Sign up to request clarification or add additional context in comments.

4 Comments

That would work but you can just use pm.response.json()[0] you don't need to declare a variable to parse the response data. Also, this will only work if you want to get the first object in the list and you would need to loop through array to get other values from other objects.
I got what you mean! The code what you sent isn't executable: response is not defined But I rewrote the request this way: pm.environment.set("deviceUUID", pm.response.json()[0].id); pm.environment.set("deviceId", pm.response.json()[0].deviceId); And it works! Thank you!
That works if you're using the native app and not the older chrome extension pm.environment.set("deviceUUID", pm.response.json()[0].id) - You basically had it correct but you were missing the [0], in your example.
Yep, I didn't know how to get the exact [0] cell in context of json() function. Thank you again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.