Sharing tips and tricks with others in the Postman community

Sending an array in a request using a data file in runner

I came across multiple questions around using an array in the part of a request body etc. using a data file in the collection runner, so here’s how you can get it working.

The solution is to extract the array out of the data variable, then since local variables have a higher scope than the data variable so you can stringify the array and store it in a local variable.
You can read more about the different types of variables and their scopes here.

You can also make use of a different type of variable type like the environment or global but then in that case you’ll have to give your variable a different name in the request body (if you’re confused here, don’t worry you’ll figure it out after reading further).

For eg:.
My data file is a JSON file and it has the following content in it:

[
  {
    "productLine": [
      {
        "id": "13jj443",
        "name": "postman"
      },
      {
        "id": "9039dds",
        "name": "newman"
      }
    ]
  },
  {
    "productLine": [
      {
        "id": "8349dfkl",
        "name": "postman-api"
      },
      {
        "id": "4590yuqp",
        "name": "api-network"
      }
    ]
  }
]

And I need to send the productLine array of each iteration as a part of my request body to the server.

Steps:

  1. In my Pre-request script, I need to get the data from the iteration data of the run.
    Code:

    let productLine = pm.iterationData.get('productLine');
    
  2. I need to stringify the productLine array and store it in a local variable (since local variables have higher precedence over data file variables so they will be used in the request-sending flow) in the script.
    Code:

    pm.variables.set('productLine', JSON.stringify(productLine));
    
  3. In my request body, I need to make sure I don’t have any quotes (") around my productLine variable that I am using:
    For eg:

    {
      "productLine": {{productLine}}
    }
    
  4. That would be all, fire it away!

8 Likes