Aleksandre Bregadze
Aleksandre Bregadze

Reputation: 339

How can I JSON.parse request body correctly in postman

My goal is to set environment variable from responseBody so I could reuse it later on in other requests. Before I do that I want to first fetch that variable, however I encounter issues.

So my responseBody looks like:

{
"email":"test_email",
"tokens":"{'refresh': 'sample_refresh', 'access': 'sample access'}"
}

Note that tokens are passed as string. Here is the code in postman tests section:

response = JSON.parse(responseBody);
tokens = response.tokens
accesstry1 = tokens["access"]
accesstry2 = tokens[1]

console.log(tokens)
Result: "{'refresh': 'sample_refresh', 'access': 'sample access'}"
console.log(accesstry1)
Result: undefined
console.log(accesstry2)
Result: "'"

I also tried to parse tokens variable but it gave me an error:

tokens = response.tokens 
tokens_parsed = JSON.parse(tokens)
Result JSONError: Unexpected token '\'' at 1:2 {'refresh': 
       'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVza

Upvotes: 0

Views: 3198

Answers (1)

gkns
gkns

Reputation: 720

Use only double quotes in JSON, When in doubt check the validity of JSON using https://jsonlint.com/ or similar tools.

This works for me:

var respText = "{\r\n\t\"email\": \"test_email\",\r\n\t\"tokens\": {\r\n\t\t\"refresh\": \"sample_refresh\",\r\n\t\t\"access\": \"sample access\"\r\n\t}\r\n}";
var respJson = JSON.parse(respText);
console.log(respJson.tokens.access);

PS: I converted the json to single line escaped string using: https://www.freeformatter.com/json-escape.html

Upvotes: 2

Related Questions