How to save a value from response as a environment variable

Hello, I’m totally new to test automation in postman.
What I wanted to do:
I call POST endpoint which returns only session-id in JSON format:
“session-id”: “234wer234wer”
In the Tests section, I wanted to save this session_id as an environment variable to use it as a header in next endpoints:

var jsonData = JSON.parse(responseBody);
pm.environment.set("SessionId", jsonData.session-id);

SessionId - is the name of the environment variable which I added earlier.

But after calling the endpoint, code in Test section fails with this error:

ReferenceError: id is not defined

And I’m not sure how to change it to get the result I want.

Hey @aalamakowiecc,

Welcome to the community! :star:

As that property key has the - character, you would need to use bracket notation to reference it.

This should be what you need:


great! thanks a lot, it helped! :slight_smile:
but it’s saved in variable as null, so session-id is not passed correctly somehow:

sorry my mistake, all is working now :slight_smile: many thanks for your help :slight_smile:

1 Like

hello @dannydainton,
I have one more question - I moved to next requests, and I tried to use similar structure in Test sections for a different request:

var jsonData = JSON.parse(responseBody);
pm.environment.set("eventId", jsonData["event_id"]);

but currently, instead of event_id in variable value I’m getting null, any idea why? This is the response of the request:

    "events": [
            "event_id": "23423werwer234",
            "event_location": "theatre"

The event_id property is inside an object {} which is inside the events array [].

You need to add event to the path and then reference the position of the object within the array, in your case, it’s the first object so that would be [0] as the list is zero-indexed.

let jsonData = pm.response.json();

If you had more than 1 object and you wanted to store each event_id as a variable, you can loop through the array:

let jsonData = pm.response.json().events

jsonData.forEach((item, index) => {
    pm.environment.set(`eventId-${index}`, item["event_id"])

many thanks for your explanation! it works : )

1 Like