Reputation: 31
I collected data from the response and pushed it into array in 'Tests'. console.log
shows that I received array:
Then I saved it into environment variable to use in the next call. But value in the request was a string, so only the first value was running.
How can I set normal array?
Response from I collected data:
{
"sent": 0,
"remaining": 1000000,
"gifts": [
{
"id": 43468,
"amount": 50000,
"can_gift_back": true
},
{
"id": 43469,
"amount": 50000,
"can_gift_back": true
}
]
}
My code in the "Tests" tab:
let jsonData = pm.response.json();
let gifts = jsonData.gifts;
//calculate array length
function objectLength(obj) {
var result = 0;
for(var prop in obj) {
if (obj.hasOwnProperty(prop)) {
result++;
}
}
return result;
}
let arrayLength = objectLength(gifts);
//push response data to the array
var giftsArray = [];
for (var i = 0; i < arrayLength; i++) {
var giftsIDs = gifts[i].id;
giftsArray.push(giftsIDs);
}
pm.environment.set("giftsToCollect", giftsArray);
UPD:
Point 1 from the picture describes the way of behavior when stringify
is used
Point 2 describes behavior when stringify
is not used
2. Example of request JSON with manually inputed ids
Upvotes: 3
Views: 5842
Reputation: 31
The working hack is to add pm.sendRequest
with the data from the second test to the "Tests" tab of the 1st test. In this case the 2d test does not run on the whole, but gifts are collected. It is not the best decision, but it works.
let jsonData = pm.response.json();
let giftsArray = [];
_.each(pm.response.json().gifts, (item) => {
giftsArray.push(item.id);
});
pm.sendRequest({
url: 'http://url/api/gifts/collect',
method: 'POST',
header: {
'Content-type': 'application/json',
'Host': 'url',
'accept-encoding': 'gzip, deflate',
'Connection': 'keep-alive'
},
body: {
mode: 'raw',
raw: JSON.stringify({'api_token': '48696295110ba1e8f9937820dc9b6626', 'user_id': '100650741100901', 'gift_ids': giftsArray, 'version': '6.0.0'})
}
}, function (err, res) {
console.log(res);
});
Upvotes: 0
Reputation: 25851
You could capture all the id
values in an array using Lodash, which is an external module that you can use in the Postman application.
Saving the array
as a variable after this, is the same as you have done so already but I've added JSON.stringify()
around the array value or it will save this as a string.
let giftsArray = []
_.each(pm.response.json().gifts, (item) => {
giftsArray.push(item.id)
})
pm.environment.set('giftsToCollect', JSON.stringify(giftsArray))
You should then be able to reference the environment variable like this:
gift_ids: {{giftsToCollect}}
I've mocked out the request data locally, just to show you this capturing the values from the data.
Upvotes: 3