Reputation: 19
I am struggling to extract the data from an array within an array to set as a variable. How would I set the variable from the ID, listed within address
{
"user profile":{
"email_address" : "[email protected]",
"addresses" : [
{
"id": 1
},
{
"id": 2
},
]
For a single array I use
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("AddressID",data.user_address[data.addresses.length-1].id);
I'm not quite sure how to use the console log as advised yesterday, if that is the answer to this issue.
Many thanks
Upvotes: 1
Views: 1234
Reputation: 123
var data = JSON.parse(responseBody); // this will store api response into variable named as data
var len=data.addresses.length; // this is evaluating length of array named as addresses in api response and saving length in variable named as len.
var envvar_akeyvalue=[]; // Here a variable is declared named as envvar_akeyvalue and variable type is defined as array using =[], to begin with it's an empty array
var j=0; //Another variable declared named as j
for (var i=0; i<len; i++) // Here a loop is executed starting from array position 0 until value of len obtained in line 2 of code
{
envvar_akeyvalue[j]=data.addresses[i].id; j=j+1; //this is capturing value of id from addresses array and saving it an array named as envvar_akeyvalue
}
postman. setEnvironmentVariable("id", envvar_akeyvalue); // this is telling postman to set environment variable with name id and obtain it's value(s) from variable envvar_akeyvalue
Upvotes: 2