JSON Response always sets variable as null, even though the response contains a value

I am trying to execute a series of API calls using a unique identifier which is unknown at the start of the calls.

I can obtain the unique identifier in my first call, cannot get the returned value to set as the environment variable.

I have run a GET call to lookup the unique identifier, the returned result is below:
[
{
โ€œKeyโ€: 4
}
]

Under the Tests tab I have defined:
const jsonResponse = pm.response.json();
pm.environment.set(โ€œKeyโ€, pm.response.json().Key);

I can see that it creates the environment variable, but the value set for the variable is โ€œnullโ€ instead of โ€œ4โ€ in the example above.

Hi @kjc22

I notice that you are using pm.response.json().Key inside the environment set, but in the line above you set that value to the variable name โ€œjsonResponseโ€ so you can just use jsonResponse[0].key

The bit that you are missing to make this work is the array index. Your response is enclosed in square brackets which means you are working inside of an array. The index of an array starts at 0 so you need to add this when you reference the response variable. Like this;


Your code would look something like this;

const jsonResponse = pm.response.json();
pm.environment.set(โ€œKeyโ€, jsonResponse[0].key);
1 Like