'How to send JSON object as JSON String with Postman?
I want to send a JSON request but problem is I need to send my userPropertiesAsJsonString field as JSON string.
How can I send userPropertiesAsJsonString as JSON string?
{
"User" : {
"userId" : "11111",
"userPropertiesAsJsonString" : ?
}
}
userPropertiesAsJsonString is;
{
"properties" : {
"propertyName" : "test",
"propertyDesc" : "desc"
}
}
Solution 1:[1]
Try this :
{
"User" : {
"userId" : "11111",
"userPropertiesAsJsonString" : "{\"properties\" : {\"propertyName\" : \"test\",\"propertyDesc\" : \"desc\"}}"
}
}
Solution 2:[2]
Jason Mullings' answer did not work for me, but it was an excellent base that allowed me to come up with a solution to a problem very similar to yours.
In the Pre-request Script tab,
const userPropertiesAsJsonString = {
"properties" : {
"propertyName" : "test",
"propertyDesc" : "desc"
}
}
pm.environment.set(
'userPropertiesAsJsonString',
JSON.stringify(JSON.stringify(userPropertiesAsJsonString))
);
Then, in the Body tab,
{
"User" : {
"userId" : "11111",
"userPropertiesAsJsonString" : {{userPropertiesAsJsonString}}
}
}
Stringifying the userPropertiesAsJsonString variable twice will allow you to escape the JSON string (solution obtained from this answer; refer to this gist for a more detailed explanation) which will then allow you to obtain a request body that looks like the one in the answer provided by sanatsathyan.
Solution 3:[3]
pre-request script:
let query = {}
pm.environment.set('query', JSON.stringify(query));
body:
{{query}}
Solution 4:[4]
As JSON means JavaScript Object Notation, so you can just copy the userPropertiesAsJsonString into the original JSON:
{
"User" : {
"userId" : "11111",
"userPropertiesAsJsonString" : {
"properties" : {
"propertyName" : "test",
"propertyDesc" : "desc"
}
}
}
}
Copy and paste this JSON into the Postman request body (raw formatted) and set the header "Content-Type: application/json".
If you have to do more fancy stuff before the request you can execute a pre-request script in Postman: https://www.getpostman.com/docs/postman/scripts/pre_request_scripts
For more about JSON see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
Solution 5:[5]
Similar to other answers but:
pm.variables.set('myJsonAsEscapedString',JSON.stringify(`{"user_id": 1, "name": "Jhon"}`))
That way you can use it without escaping explicitly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sanatsathyan |
| Solution 2 | sabriele |
| Solution 3 | Jason Mullings |
| Solution 4 | |
| Solution 5 | alexaner |
