Saving environment variables in an array

Hi

I get the following response from a GET request that I send:

[
  {
    "Id": 1,
    "Name": "Bank1",
    "site": "London",
    "Count": 27,
    "active": false
  },
  {
    "Id": 2,
    "Name": "Bank2",
    "site": "Manchester",
    "Count": 412,
    "active": false
  },
  {
    "Id": 3,
    "Name": "Bank3",
    "site": "Birmingham",
    "Count": 763,
    "active": true
  }
]

I am trying to save all of the ‘site’ responses to be used in my following request by creating the following test:

var jsonData = JSON.parse(responseBody);
pm.environment.set("site1", jsonData.site[0]);

However, my environment variable ‘site1’ is null when I was expecting London.

Can anyone advise me how I get the variable saved with the actual response for all 3 of the fields called site ?

Many thanks

With the current JSON response provided, the below snippet could work.

var jsonData = JSON.parse(responseBody);
console.log(jsonData[0].site);
pm.environment.set("site1", jsonData[0].site);

siteArray = [];
for (var i=0; i<jsonData.length; i++)
{
    var site = jsonData[i].site;
    //console.log(jsonData[i].site)
    siteArray.push(`${site}`);
}
console.log(siteArray);

image

Hey @carterusm69

To save each site value to an individual variable you could use something like this to loop through the objects of the response array. I’ve set them as global variables here but you can just which the scope to your needs.

_.each(pm.response.json(), (el, index) => pm.globals.set(`site${index + 1}`, el.site))

The index is there to give you a unique name but as it’s zero indexed, i’ve added a +1 to make it more human readable.

Or if you do want to store these are an array in a variable:

let sites = []
_.each(pm.response.json(), (el) => sites.push(el.site))

pm.globals.set("sites", JSON.stringify(sites))

To use them in a request, you would need to parse the array in the Pre-request Script to access each value:

let site = JSON.parse(pm.globals.get('sites'))

console.log(site[0])
console.log(site[1])
console.log(site[2])