Collection Runner: sending requests with array of objects read from data source file

Hello,

I am sending request wit couple of string, boolean fields. I have many requests so I am sending it via RUNNER. I would need as well to send array of objects so in my real request it looks something like:

    "Variants": [  {  "EAN": "ean1",        "ReservedStock": 10,        "Price": 20,      },      {        "EAN": "ean2",        "ReservedStock": 100,        "Price": 200      }    ],

My raw request:

{
  "id": "DomainProduct/__NEW__",
  "ProductDetails": {
    "ERPNumber": "{{ERP_NUMBER}}",
    "LidlProductNumber": "{{LIDL_PRODUCT_NUMBER}}",
    "ProductName": "{{SHORT_DESCRIPTION}}",
    "OnlineProduct": {{ONLINE_PRODUCT},
    "Variants": "{{VARIANTS}}"
  }
}

In prerequest script I have:

pm.environment.set('VARIANTS', JSON.stringify(data.VARIANTS));

In my source file:

[
  {
    "ERP_NUMBER": "000000000100007147",
    "LIDL_PRODUCT_NUMBER": "123456",
    "SHORT_DESCRIPTION": "Calvin Klein MGM WE Regression 1.1_17 Sammel",
    "PRICE": 200.89,
    "ONLINE_PRODUCT": true,
     "VARIANTS": [
      {
        "EAN": "ean1",
        "ReservedStock": 10,
        "Price": 20,
      },
      {
        "EAN": "ean2",
        "ReservedStock": 100,
        "Price": 200
      }
    ],
  }
]

Problem is that variants are not sent.

Can someone help me?

Can you remove the quotes(") around the VARIANTS variable in the request body and try it out?

Update it like so:

{
  "id": "DomainProduct/__NEW__",
  "ProductDetails": {
    "ERPNumber": "{{ERP_NUMBER}}",
    "LidlProductNumber": "{{LIDL_PRODUCT_NUMBER}}",
    "ProductName": "{{SHORT_DESCRIPTION}}",
    "OnlineProduct": {{ONLINE_PRODUCT},
    "Variants": {{VARIANTS}}
  }
}

Adding the quotes around it, converts it to a string.

@josefmgm
Noticed that you’re using the environment variable to stringify and store the variable from the data file.
But data file has higher precedence over the environment variable so whenever that you’re running the request, it’s still picking up the value of the variable from the data file instead of what you’ve set.

Docs for variables and their scopes: https://learning.getpostman.com/docs/postman/environments_and_globals/variables/#variable-scopes

Solution:

  1. Make use of local variables since it has higher precedence over the data variable.
    So you have to change your pm.environment.set to pm.variables.set

  2. Use a different name in the request body, so instead of {{VARIANTS}}, use something like: {{ENV_VARIANTS}} and update your environment variable name in case you still need to use the environment

Something like this:

pm.environment.set('ENV_VARIANTS', JSON.stringify(data['VARIANTS']));

It worked! Thanks for the quick support!

1 Like