# Postman Pre-Request Script to Read Variables from CSV file and Append to JSON Body

**URL:** <https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603>\
**Category:** Help Hub\
**Tags:** variables, json, python, javascript\
**Created:** [June 27, 2022, 7:47pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603 "2022-06-27T19:47:55Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![evidence8321](https://avatars.discourse-cdn.com/v4/letter/e/e274bd/32.png) [@evidence8321](https://community.postman.com/u/evidence8321)\
**Post date:** [June 27, 2022, 7:47pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/1 "2022-06-27T19:47:55Z")

</div>

I have a JSON body with template to pass to an API endpoint in Postman/Newman as follows:

```auto
{
  "total": [
    {
      "var1a": "ABCDE",
      "var1b": {
        "var2a": "http://url/site/{{yyyy}}/{{mmdd}}/{{yyyymmdd}}.zip",
        "var2b": {
           "var3a": "{{yyyymmdd}}",
           "var3b": "GKG"
        },
        "var2c": "ABCDE"
        "var2d": "{{p}}"
      }
    },
    {
      "var1a": "ABCDE",
      "var1b": {
        "var2a": "http://url/site/{{yyyy}}/{{mmdd}}/{{yyyymmdd}}.zip",
        "var2b": {
           "var3a": "{{yyyymmdd}}",
           "var3b": "GKG"
        },
        "var2c": "ABCDE"
        "var2d": "{{p}}"
      }
    }
}

```

Everything enclosed in double braces is a variable that needs to read from an external CSV file, which looks like:

```auto
p,yyyymmdd,yyyy,mmdd
1,19991231,1999,1231
2,20001230,2000,1230

```

- Note that the CSV isn’t necessarily 2 entries long - I’d ideally like it to take in a dynamic number of entries that append after the last.
- Ideally, I’d get rid of the last two columns in the CSV file (`yyyy` and `mmdd`) and have the code just do a slice as needed.

How do I even begin coding the pre-request script?

Even if reading from an external CSV is not possible, or even coding within the pre-request script to do this, what is a quick one-liner in Javascript or Python that can quickly give me the output I need so that I can just manually place it in the request body?

I even tried using the Postman runner to do a “fake” run so that I can quickly extract the different JSON bodies, but even with this, there is no clean way that it does the export…

---

<div class="post-metadata">

**Author:** ![w4dd325](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/w4dd325/32/12436_2.png) [@w4dd325](https://community.postman.com/u/w4dd325)\
**Post date:** [June 27, 2022, 8:06pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/2 "2022-06-27T20:06:50Z")

</div>

Hi @evidence8321

I haven’t full digested your question yet but in terms of splitting the value you could do something like this;

```auto
let date = 20220627; // <-- Change to variable from CSV
let dateAsString = date.toString();

let year = dateAsString.substr(0, 4);
let monthDay = dateAsString.substr(4, 4);

console.log("year = ", year);
console.log("monthDay = ", monthDay);

```

Output;  
 ![image](https://us1.discourse-cdn.com/getpostman/original/2X/d/d5a179ff3dbb022c222be44fbaea5144d88d27b8.png)

---

<div class="post-metadata">

**Author:** ![w4dd325](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/w4dd325/32/12436_2.png) [@w4dd325](https://community.postman.com/u/w4dd325)\
**Post date:** [June 27, 2022, 8:09pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/3 "2022-06-27T20:09:43Z")

</div>

> [@evidence8321](#):
>
> Note that the CSV isn’t necessarily 2 entries long - I’d ideally like it to take in a dynamic number of entries that append after the last.

Could you explain this in a little more detail, please?

---

<div class="post-metadata">

**Author:** ![evidence8321](https://avatars.discourse-cdn.com/v4/letter/e/e274bd/32.png) [@evidence8321](https://community.postman.com/u/evidence8321)\
**Post date:** [June 27, 2022, 8:43pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/4 "2022-06-27T20:43:00Z")

</div>

> [@evidence8321](#):
>
> ```auto
> p,yyyymmdd,yyyy,mmdd
> 1,19991231,1999,1231
> 2,20001230,2000,1230
> 
> ```

Thanks! Yes - this explains perfectly how to split the value - I can hopefully get rid of those last two columns.

To clarify on the bigger problem…

What I meant was, the “input” CSV could look anything like:

```auto
p,yyyymmdd,yyyy,mmdd
1,19991231,1999,1231
2,20001230,2000,1230

```

OR

```auto
p,yyyymmdd,yyyy,mmdd
1,19991231,1999,1231
2,20001230,2000,1230
3,19991231,1999,1231
4,20001230,2000,1230
5,19991231,1999,1231
6,20001230,2000,1230

```

ie. I’d like the JSON body to read the variables from any number of rows from a given CSV using just the template JSON:  
“var1a”: “ABCDE”,  
“var1b”: {  
“var2a”: “[http://url/site/{{yyyy}](http://url/site/%7B%7Byyyy%7D)}/{{mmdd}}/{{yyyymmdd}}.zip”,  
“var2b”: {  
“var3a”: “{{yyyymmdd}}”,  
“var3b”: “GKG”  
},  
“var2c”: “ABCDE”  
“var2d”: “{{p}}”  
}  
},  
…

---

<div class="post-metadata">

**Author:** ![w4dd325](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/w4dd325/32/12436_2.png) [@w4dd325](https://community.postman.com/u/w4dd325)\
**Post date:** [June 27, 2022, 9:04pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/5 "2022-06-27T21:04:10Z")

</div>

I think this is what you are looking for;  
Being able to manipulate the iterations based on the total row count in your CSV.

> [@Perform actions on the basis of iteration count in Collection Runner](https://community.postman.com/t/perform-actions-on-the-basis-of-iteration-count-in-collection-runner/2739/2):
>
> Hey @gherghinoiu, the good news is that it’s solvable! So, if you scroll down the docs - [https://www.getpostman.com/docs/v6/postman/scripts/postman\_sandbox\_api\_reference](https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference) You’ll see that in the pm.info object, there’s a property called as iterationCount which is the total number of iterations that are scheduled to run. Now, Total number of iterations === Number of rows in your CSV File Also, instead of using the response\_array.length you can use another property of the pm.info object viz. p…

If it’s not, let me know… I may have misunderstood your need.

---

<div class="post-metadata">

**Author:** ![evidence8321](https://avatars.discourse-cdn.com/v4/letter/e/e274bd/32.png) [@evidence8321](https://community.postman.com/u/evidence8321)\
**Post date:** [June 27, 2022, 9:10pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/6 "2022-06-27T21:10:17Z")

</div>

I would like to run the request only **once** - so a runner is not useful here.  
Before running the request, I’d like the JSON body to read by iterating over the input CSV (w/ reading from the pre-request script), and then run the request.

---

<div class="post-metadata">

**Author:** ![w4dd325](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/w4dd325/32/12436_2.png) [@w4dd325](https://community.postman.com/u/w4dd325)\
**Post date:** [June 28, 2022, 12:46am UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/7 "2022-06-28T00:46:06Z")

</div>

Hopefully, this makes sense… It’s 1:45 am and I’m very tired 🤣

So if my understanding is correct, you are trying to loop through a CSV to build a payload, that can then be sent as a request body for a subsequent call.

If this is correct then the below code should give you what you need…

Note: Request 1 **has to loop** through all the rows so the iteration count has to be set to the number of rows. Otherwise, you will not see the total row count for the CSV.

 ![image](https://us1.discourse-cdn.com/getpostman/original/2X/c/c765e6a5b254b2ae382d968b36f1e223a8fdc167.png)

But we will use `postman.setNextRequest()` to control when the second request gets triggered;  
 ![image](https://us1.discourse-cdn.com/getpostman/original/2X/b/b424ff1bee8ee7132823591756e56af889054342.png)

* * *

**The code;**

```auto
//Get 'p' and 'date' from CSV and set as collection level variables 
pm.collectionVariables.set("p", pm.iterationData.get('p'));
pm.collectionVariables.set("date", pm.iterationData.get('yyyymmdd'));
//Convert to strings
let pAsString = pm.collectionVariables.get("p").toString();
let dateAsString = pm.collectionVariables.get("date").toString();
//Use substr to get only part of the string
let year = dateAsString.substr(0, 4);
let monthDay = dateAsString.substr(4, 4);
//----------------------------------------------------------
if(pm.info.iteration === 0){
    //If it's the first iteration, declare a fresh array
    let myArray = [];
    //Push the new value to array 
    myArray.push('{"var1a":"ABCDE","var1b":{"var2a":"http://url/site/' + year + '/' + monthDay + '/' + dateAsString + '.zip","var2b":{"var3a":"' + dateAsString + '","var3b": "GKG"},"var2c":"ABCDE""var2d":"' + pm.iterationData.get('p') + '"}}');
    //Save array to collection variables
    pm.collectionVariables.set("myArray", myArray);
}
else if(pm.info.iteration > 0){
    //If it is not the first iteration then set myArray to the value of the current saved array
    let myArray = pm.collectionVariables.get("myArray");
    //Push the new value to array 
    myArray.push('{"var1a":"ABCDE","var1b":{"var2a":"http://url/site/' + year + '/' + monthDay + '/' + dateAsString + '.zip","var2b":{"var3a":"' + dateAsString + '","var3b": "GKG"},"var2c":"ABCDE""var2d":"' + pm.iterationData.get('p') + '"}}');
    //Save array to collection variables
    pm.collectionVariables.set("myArray", myArray);
}
//----------------------------------------------------------
if (pm.info.iteration === (pm.info.iterationCount-1)){
    //If the iteration is the same number of rows in the CSV then go to Request 2
    postman.setNextRequest("req2");
}
else{
    //If the iteration is NOT the same number of rows in the CSV (It hasn't reached the end of the file) then do nothing
    postman.setNextRequest(null);
}

```

* * *

Once this completes, request 2 outputs the full array that has been built using `pm.collectionVariables.get("myArray");`. This variable would be your payload.

Example of output;

 ![image](https://us1.discourse-cdn.com/getpostman/original/2X/1/160d1f316f9de1b7cd008be86ac80b0b7ba9b125.png)

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [December 12, 2024, 12:54pm UTC](https://community.postman.com/t/postman-pre-request-script-to-read-variables-from-csv-file-and-append-to-json-body/36603/8 "2024-12-12T12:54:13Z")

</div>

Closed on December 12, 2024, 12:54pm UTC

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
