Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array from variable is sent like a string in Postman

I collected data from the response and pushed it into array in 'Tests'. console.log shows that I received array:

enter image description here

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.

enter image description here

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:

  1. After using code from the answer in different ways I received such issue.

Point 1 from the picture describes the way of behavior when stringify is used

Point 2 describes behavior when stringify is not usedenter image description here 2. Example of request JSON with manually inputed ids enter image description here

like image 878
Mika Avatar asked Oct 20 '25 05:10

Mika


1 Answers

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.

Postman

like image 50
Danny Dainton Avatar answered Oct 21 '25 21:10

Danny Dainton