My question:
I’m working on chaining calls together to take the copy/pasting pain out of testing. I’m trying to pull a value from the JSON response body, save it as an Environment Variable which I can then use in another call.
My issue is that I can’t seem to get the value I need populated in my environment variables. It’s not just this specific variable; I can’t get any of them to show up.
I’ve tried a couple approaches, courtesy of Postman documentation, which I’ll paste below. The name of the variable shows up in the Environment Variables, but the value is always null.
In the Tests tab:
// Access the JSON response body
let response = pm.response.json();
// Extract usr_key from response
let usrKey = response.users.id;
pm.environment.set("usrKey", usrKey);
// Alternate approach, also fails.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("id", jsonData.users.id);
*Here’s an example of a response. The value I’m attempting to extract is the 7-digit “id”:
It’s very orthodox in your scenario The square brackets at the start and end of the users section indicates that technically your response could contain multiple users (therefore you have to specify [0] because in Javascript-land that means “the first item in the list”).
It’s worth bearing in mind, just in case you have edge-cases where multiple users come back and you might not necessarily want to grab the id of the first one.
If you do have a situation where you are storing more than 1 item in the array, just store the whole array as a variable and loop through it later. Using only index 0, as neilstudd said, will only get you the first one.
For example, if a company puts jobs in trays and they want the entire list of active trays in an array it might look something like this:
//Gets only the non-null jobID's (tray numbers) and puts them into an array.
The JS masters may have a way better way to do this, but this is how we currently do it.
let trayIDs = response.data.order.filter(function (order) {
if(order.jobID == ""){
return false;
}
return true;
}).map(order => order.jobID);
pm.environment.set("trayIDs", JSON.stringify(trayIDs));