Reputation: 5246
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"
}
}
Upvotes: 24
Views: 91747
Reputation: 1195
In general, when you want to store json as variable, double quotes (string representation) is not required:
Example:
Now, in the request body, DO NOT use quotes,
Upvotes: 1
Reputation: 11
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.
Upvotes: 1
Reputation: 656
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.
Upvotes: 29
Reputation: 1042
pre-request script:
let query = {}
pm.environment.set('query', JSON.stringify(query));
body:
{{query}}
Upvotes: 8
Reputation: 687
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
Upvotes: 2
Reputation: 1773
Try this :
{
"User" : {
"userId" : "11111",
"userPropertiesAsJsonString" : "{\"properties\" : {\"propertyName\" : \"test\",\"propertyDesc\" : \"desc\"}}"
}
}
Upvotes: 35