MathBob
MathBob

Reputation: 107

Postman: Get data from JSON file in Pre-request Script

I am trying to find a way to use data from my .json file in the pre-request script in Postman. As you can see in the code below I am using a loop for my request. In my pre-request script i would like to use "id_group":"14803,14805" from my file Data.json instead of id_group = ["14803","14805"];.

Thanks

URL:

.../group/{{id_of_group}}/members

Body:

    {
     "id_user": {{id_user}}
    }

Pre-request script:

var id_group = pm.environment.get("id_group");

if (!id_group) {
    id_group = ["14803","14805"];
}   

var currentIdGroup = id_group.shift();
pm.environment.set("id_of_group", currentIdGroup);
pm.environment.set("id_group", id_group);

Tests:

var id_group = pm.environment.get("id_group");
console.log(id_group);
if (id_group && id_group.length > 0) {
   postman.setNextRequest('Add user to groups');
} else {
   postman.setNextRequest();
}

Data.json file:

[{
 "id_user":47091,
 "id_group":"14803,14805"
}]

Upvotes: 0

Views: 8894

Answers (2)

MathBob
MathBob

Reputation: 107

I have just found an answer. In the pre-request script I use the variable id_group, this variable is used to get the id's which are going to be used in the loop.

I found pm.iterationData.get();, it will take the data from the JSON file. Instead of id_group = ["14803","14805"]; I use pm.iterationData("id_group").

My pre request script look like this now:

var id_group = pm.environment.get("id_group");   

    if (!id_group) {
        id_group = pm.iterationData.get("id_group");
    } 

    var currentIdGroup = id_group.shift();
    pm.environment.set("id_of_group", currentIdGroup);
    pm.environment.set("id_group", id_group);

And I cheat a little, my JSON look like this now:

[{
 "id_user":47091,
 "id_group":["14803","14805"]
}]

Upvotes: 1

DieGraueEminenz
DieGraueEminenz

Reputation: 880

You are creating an Array-Object. But the pm.environment.set() stores only strings. You must convert them into strings with JSON.stringify().

Instead of pm.environment.set("id_of_group", currentIdGroup); i would suggest

pm.environment.set("id_of_group", JSON.stringify(currentIdGroup));

And backwards the same. If you are loading from the env vars, you have to parse your stringified objects: JSON.parse(pm.environment.get("id_group"));

Upvotes: 1

Related Questions