0

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
Aleksandre Bregadze
  • 199
  • 1
  • 3
  • 14

1 Answers1

2

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

gkns
  • 697
  • 2
  • 12
  • 32
  • Mhh actually interesting links, I will try to use them from now on... Strangely, I checked and I am passing keys in double quotes from backend, I will look furthermore why it switched like this. But, test_email, sample_refresh and sample_access these are dynamic variables. For every request they will be different and hardcoding this wont work will it? – Aleksandre Bregadze Dec 28 '21 at 08:52
  • `respText` is a variable, so any valid and escaped JSON (as if produced by `JSON.stringify()` method, should work, no hardcoding) – gkns Dec 28 '21 at 09:01
  • I mean `respText = "{\r\n\t\"email\": \"test_email\"` this cannot be hardcoded like you have in example because different users have different email... `respText = "{\r\n\t\"email\": \"test1@email.com\"` `respText = "{\r\n\t\"email\": \"test2@email.com\"` and etc... – Aleksandre Bregadze Dec 28 '21 at 09:12