Fernando Rengifo
Fernando Rengifo

Reputation: 23

How to set a JSON string to Postman variable and use it in the Body?

In Postman, I want to pass a dynamic JSON string to a variable and use it in a request. This is what I have:

Pre-request:

var myJsonString = "{ \"type\": \"10\", \"number\": \"123456\" }";

pm.variables.set("my-json-string", myJsonString);

Body:

"body":{
     "jsonString":"{{my-json-string}}"
}

But this does not work. Do you know any solution for this?

If I send the request like this, it works perfect:

"body":{
     "jsonString":"{ \"type\": \"10\", \"number\": \"123456\" }"
}

Upvotes: 2

Views: 5217

Answers (2)

Michael Cauduro
Michael Cauduro

Reputation: 215

you need to store it using JSON.stringify

let response = pm.response.json(),
jsonVariable = JSON.stringify(response);
pm.environment.set("yourVariable", jsonVariable );

And then use it in another like:

"yourVariable":"{{yourVariable}}",

Upvotes: 0

Danny Dainton
Danny Dainton

Reputation: 25921

Have you tried wrapping it with JSON.stringify()?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

pm.globals.set("my-json-string", JSON.stringify(myJsonString))

As this value is saved as a string, you will not need to use the delete double-quotes on variable within the Post body:

"jsonString":{{my-json-string}}

Upvotes: 1

Related Questions