How to store the response body as a JSON variable?

Hi Folks!

Iā€™m new to Postman and I have no sweet clue about coding. The only thing I kind of know is Excel VBA :stuck_out_tongue:

I was following along with a previous question posted in 2018 (linked below) about how to store a JSON in a variable. I was able to get it to work but I donā€™t know how to clean up the response.

Note that the variable Iā€™m trying to save is the Connection ID so it changes every time, so Iā€™ve set the pre-request to clear the variable before the main call.

Thanks in advance!!! :pray: :blush:

Pre-Request

pm.collectionVariables.clear(ā€œconnectionIDā€)

Body

POST: https://stuff.com/(site share name)/ws/JSONBridge.cfm

{
ā€œargumentsā€:{
ā€œapiKeyā€:ā€œ1234ā€,
ā€œlogoutCurrentWebConnectionā€:false
},
ā€œmethodNameā€:ā€œconnectWithApiKeyā€,
ā€œserviceNameā€:ā€œConnectionServiceā€
}

Result

{
ā€œresultā€:ā€œ(site share name)-(unique session ID)ā€
}

Post-Response

let response = pm.response.json(),
connectionID = JSON.stringify(response);
pm.collectionVariables.set(ā€œconnectionIDā€, connectionID);

The saved variable then looks like this
connectionID= ā€œresultā€:ā€œ(site share name)-(unique session ID)ā€
when I really need it to be this
connectionID= (site share name)-(unique session ID)

How to store a JSON in a variable and use it in the request body?

let response = pm.response.json();
pm.collectionVariables.set("connectionID", response.result);
console.log(pm.collectionVariables.get("connectionID")); // "(site share name)-(unique session ID)"
1 Like

Thank you so so much! Youā€™re a wizard!

Question,

Whatā€™s the difference between

let response = pm.response.json();
pm.collectionVariables.set(ā€œconnectionIDā€, response.result);
console.log(pm.collectionVariables.get(ā€œconnectionIDā€));

let response = pm.response.json(),

connectionID = JSON.stringify(response);

pm.collectionVariables.set(ā€œconnectionIDā€, connectionID);

In your original code, you were stringifying the whole response and then storing that as the collection variable.

Where in the code I provided, Iā€™m targetting the result key directly and then storing the value of that key as the collection variable.

1 Like

Ohhhh! Gotcha!

Thank you so very much!

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