3

I am trying to set an array as an environmental variable in postman. But it stores the first value of the array rather than the array.

var aDataEntry = postman.pm.environment.get('data_set_entries');
if(aDataEntry == null) {
    aDataEntry = [];
}
var jsonData = pm.response.json();
aDataEntry.push(jsonData.dataEntry.id);

// a console.log here confirms that aDataEntry is an array

postman.pm.environment.set('data_entry',aDataEntry);

As mentioned in the comment of the code, the variable is coming as an array, but when I again get the environment variable in the second run, it is not of type array. But just contains the first element in the array.

What's wrong here? How can set the array and use it from the postman environment variable.

Kannan Ramamoorthy
  • 3,522
  • 6
  • 43
  • 60
  • Postman stores all collection/global/environment vars as strings unless you wrap the value something like `JSON.stringify()` when you're setting the environment variable. – Danny Dainton May 02 '18 at 09:30
  • Does this answer your question? [Postman: Can i save JSON objects to environment variable so as to chain it for another request?](https://stackoverflow.com/questions/41479494/postman-can-i-save-json-objects-to-environment-variable-so-as-to-chain-it-for-a) – Henke Jan 27 '21 at 11:36

1 Answers1

13

It seems like pm.environment.set calls the toString and sets the value. Using the below code to work-aorund that,

var aDataEntry = pm.environment.get('data_set_entries');
if(aDataEntry == null) {
    aDataEntry = [];
} else {
   aDataEntry = JSON.parse(aDataEntry);
}
var jsonData = pm.response.json();
aDataEntry.push(jsonData.dataEntry.id);

// a console.log here confirms that aDataEntry is an array

pm.environment.set('data_entry',JSON.stringify(aDataEntry));

For my use case, the value in the array will be simple, without any , in them. So the above work-around works for me.

Edit 1:

As gone through the reference, it is suggested to use JSON.stringify() and JSON.parse() for storing complex objects. Updating the code accordingly.

Kannan Ramamoorthy
  • 3,522
  • 6
  • 43
  • 60
  • 5
    I would replace things like `JSON.parse(responseBody)` , `postman.getEnvironmentVariable` and `postman.setEnvironmentVariable` with the newer syntax. `pm.response.json()`, `pm.environment.get()` and `pm.environment.set()` - The older stuff will start to be depreciated soon enough. – Danny Dainton May 02 '18 at 09:32
  • The `JSON.parse(aDataEntry)` will only work if you used `JSON.stringify()` when saving the `data_set_entries` environment variable, like so: `pm.environment.set('data_set_entries',JSON.stringify(dataSetEntries))`. - Right? – Henke Jan 28 '21 at 07:26