Set array from environment variable for request body in postman

I have a request where based on a environment variable i have a array of values
let flavor= “”;
if (os.toLowerCase() === “windows”) {
flavor= [“hello”,“hi”];
}
else {
flavor = [“hello”,“hi”,“how do you do”];
}
pm.environment.set(“flavor”,JSON.stringify(flavor));

Now in POST body i have the following:
{
“connection”: “{{connect}}”,
“type”: {{flavor}},
“name”: “”,
}

Unable to use the stringified array from environment vairable as an array object?
How to go about this

Hey @Ra_Na.

You could stringify and set the entire request body in an environment variable and then simply use that in the request body for the types to work correctly.

This is how it would look.

  • Pre request script
let flavor,
    requestBody = {
        "connection": "string",
        "name": "string",
    };

if (os.toLowerCase() === "windows") {
    flavor= ["hello","hi"];
}
else {
    flavor = ["hello","hi","how do you do"];
}

requestBody.type = flavor;

pm.environment.set("body", JSON.stringify(requestBody));
  • Request body - raw
{{body}}

Hope this helps.

2 Likes

Thanks @deepak.pathania