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.