1

I am new to postman API testing.
Recently I am using it's collection runner to test request iteration with data file(json). The weird thing is if I try to access the environment variable that I set before, the console log always shows [object Object] instead of Object {}.
Here's my pre-request code on postman:

postman.setEnvironmentVariable("username", data.username);
postman.setEnvironmentVariable("password", data.password);

and the Tests code on postman:

var userData = {
    username: environment.username,
    password: environment.password
};

postman.setEnvironmentVariable("user", userData);

console.log(environment.user);

for(var key in environment.user){
    console.log(key + ": "+ environment.user[key]);
}

Request URL: https://echo.getpostman.com/get?username={{username}}&password={{password}}

data.json:

[{
    "username" : "Jon Snow",
    "password" : "iloveGot123"
},{
    "username" : "Akali",
    "password" : "iWillKickyalla55"
},{
    "username" : "Ricky Grimmes",
    "password" : "rg0123455"
}]

Please help thank you.

Winfred Peng
  • 191
  • 1
  • 2
  • 9
  • 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 Feb 19 '21 at 14:12

1 Answers1

2

According to the documentation:

postman.setEnvironmentVariable(variableName, variableValue): Sets an environment variable “variableName”, and assigns the string “variableValue” to it. You must have an environment selected for this method to work. Note: Only strings can be stored. Storing other types of data will result in unexpected behavior.

https://www.getpostman.com/docs/sandbox

So basically it's showing that because it wants a string only.

You can wrap the object with JSON.stringify() to convert it to a string and then use JSON.parse() when you want to turn it back into an object.

Ethan22
  • 747
  • 7
  • 25