Trouble setting environment variable from response

I’m trying to store the ID from a response body to use in an another API push, but it is isn’t picking up the value I need. I have an environment variable for “userId” and I want the test script to set the value for that to the “id” value. Whenever I run this test though, the value doesn’t get updated.

Here is the test I am using:

var jsonData = JSON.parse(responseBody);

pm.environment.set("userId", jsonData.id);

The response body looks like this:

[
        {
            "id": "64d4dgtwac6hSTWaG4s6",
            "status": "ACTIVE",
            "created": "2016-06-02T15:06:16.000Z",
            "lastLogin": "2018-12-11T16:51:11.000Z",
            "profile": {
                "lastName": "Doe",
                "displayName": "John Doe",
                "firstName": "John",
            },
            "credentials": {
                "provider": {
                    "type": "ACTIVE_DIRECTORY",
                    "name": "domain.com"
        }
    ]

@greyson.hobbs

Try pm.environment.set(“userId”, jsonData[0].id);

Mick

1 Like

Thanks for the quick response. I tried that and it came back with this error.

There was an error in evaluating the test script: SyntaxError: Invalid or unexpected token

As @mick.mcbride suggested, if your response looks like exactly like you posted above, then you can try this:

let resp = pm.response.json();

pm.environment.set('userId', resp[0].id);

If that doesn’t work, then can you paste a screenshot of your response?

1 Like

That worked! Thank you both for you help!

How would I get the same thing to work for this? I want to pull all of the items under the “Groups” into a variable. I tried the same answer you provided for getting the ID, but it didn’t work as expected.

[
    {
        "id": 2457585,
        "name": "john.doe@domain.com",
        "groups": [
            {
                "id": 9568265,
                "name": "Main Users"
            },
            {
                "id": 2653481,
                "name": "New Group"
            },
            {
                "id": 6475824,
                "name": "Help Desk"
            },
            {
                "id": 6958234,
                "name": "Everyone"
            },
            {
                "id": 9854162,
                "name": "(Managers and Supervisors)"
            }
        ]
    }
]

You could try something like this to get that array and set it as an environment variable:

pm.environment.set("groupItemsArray", JSON.stringify(resp[0].groups))

To get each of the id values, you would need to loop through them and then set that array as the environment variable:

let groupIds = []

_.each(resp[0].groups, (item) => {
    groupIds.push(item.id)
})

pm.environment.set("groupIds", JSON.stringify(groupIds))

Is this what you were looking to do?