How to Get-Post?

Im using get method to read files from an specific folder and i receive a json like this:

value:[{
“Name”: “TEST1.txt”,
“FileName”: “TEST1.txt”,
“id”: “13255”,
}{
“Name”: “TEST2.txt”,
“FileName”: “TEST2.txt”,
“id”:“254783”
}]

On the same collection i have a Post Method because i need to copy all the existing files on another folder.

How can it be done?
i was trying to save the value in a global variable on my TEST:

pm.test(“GetId”, function () {
var jsonData = pm.response.json()
const values = pm.response.json().value;

pm.globals.set("id", jsonData.value.id)   

})

i know i should use an iteration for or a while but im not pretty sure how can it be done for this example.

Im new on postman, could you please help me?

Trying this but i get a reference error in jsondata:

for(var i=0; i<jsonData.value.id; i++)
{
if (jsonData.value[i].id!=“NULL”)
{
pm.globals.set(“id”, jsonData.value[i].id);
}

}

Please explain why iteration is skipped without error?

//pm.test("GetId", function () {
      //var jsonData = pm.response.json()
      
      var data = JSON.parse(responseBody);
      //for(var i=0; i < data.value; i++)
      
      for(var i=0; i < data.value[i] ; i++)
      {
      tests["Entra en la Iteracion "]=true;
         
      pm.globals.set("id", data.value[i].Id);
      //pm.globals.set("id", pm.response.json().Id);
      //pm.globals.set("id", JSON.stringify(responseBody.value.Id));
      // pm.globals.set("id", jsonData.value[i].id);
      //pm.globals.get("id");
      console.log("id");  
    
      }
      tests["Sin Errores Logicos"]=true;  
      
      
      
//    const values = pm.response.json().value;
//    pm.globals.set("id", jsonData.value.id)   
//})

/*for(var i=0; i<jsonData.value.id; i++)
{
    //if (jsonData.value[i].id!="NULL")
    if (jsonData.value.id[i]!="NULL")
    {
       //pm.globals.set("id", jsonData.value[i].id);
       pm.globals.set("id", jsonData.value.id[i]);
       postman.setNextRequest("Copia borrable");
    }   

}*/

@gaccerbo You need to stringify the variables before storing it to the globals.
You’ll need to write something like this:

// to set
pm.globals.set("fileValues", JSON.stringify(jsonData.value));   

and when you want to read the value of this global variable in a script you’ll have to parse it.

// to get
let values = JSON.parse(pm.globals.get('fileValues'));

The code that you shared - I am not sure what to make out of this commented code.
You’ve written an incorrect for loop.
What you’ve written is:

 // You've written i < data.value[i] ?!
for(var i = 0; i < data.value[i] ; i++)

What you actually wanted is:

 // Run the for loop starting from 0, till the the length of the array.
for(var i = 0; i < data.value.length ; i++)

Also, I don’t think so you need to separate out the values here using a loop, because you’re updating the same variable again and again with a new value, but in the end it’s always one variable i.e id.

1 Like