How to set global variables with set of value from json response?

Hi,
my request has this response:

[
{
“Site”: “google.com”,
“external”: false,
“active”: true,
“black”: false,
“AVR”: false
},
{
“Site”: “google.ca”,
“external”: false,
“active”: true,
“black”: false,
“AVR”: false
},
{
“Site”: “yulu.com”,
“external”: true,
“active”: false,
“black”: true,
“AVR”: true
}
]

I want to set global variable with each set of data like:
var1 = “Site”: “google.com”,
“external”: false,
“active”: true,
“black”: false,
“AVR”: false

var2 = “Site”: “google.ca”,
“external”: false,
“active”: true,
“black”: false,
“AVR”: false

var3 = “Site”: “yulu.com”,
“external”: true,
“active”: false,
“black”: true,
“AVR”: true

I am able to set each value in one var like for example:
var1= “Site”: “google.com”,“Site”: “google.ca”,“Site”: “yulu.com
by using this code:

> var jsonData = JSON.parse(responseBody);
var jsonNamesData = jsonData;
console.log(jsonNamesData);
var parsedData = "";
for(var i=0;i<jsonNamesData.length;i++){
parsedData = parsedData +"\"Site\" : \"" +jsonNamesData[i].Site+"\", ";
console.log("\"Site\" : \"" +jsonNamesData[i].Site+"\"");
}
pm.globals.set("Site", parsedData);

Thank you for your help.

Hey @ps198478320

You could probably achieve this with something like:

_.each(pm.response.json(), (item, index) => { 
    pm.globals.set(`var${index + 1}`, JSON.stringify(item))
})

Hi @dannydainton ,
you solution works but it stores only the last set of value:

“Site”: “yulu.com”,
“external”: true,
“active”: false,
“black”: true,
“AVR”: true

i’m looking at how to do for all set of value…

It should be looping through the whole array and setting each of the objects as a new variables.

Could you share an image of the app and how you have the code?

Did you use the code as I wrote it?

What ever the name you have chosen for the variable, this part is important ${index + 1} as it gives a unique name for the variable.

Without this, you’re going to overwrite the last stored variable and probably end up with the last one.

Yes i use exactly your code:

_.each(pm.response.json(), (item, index) => { 
pm.globals.set('item', JSON.stringify(item))

})

It’s not quite as I wrote it :grin:

You are right, i made a mistake, it works now, it goes to all value and stores in variable.
Thank you very much.

1 Like