Jeff Tian
Jeff Tian

Reputation: 5893

How to JSON.parse() deserialize a JSON.stringify serialized object which contains a stringified object?

In Chrome console, I type:

JSON.stringify({a:{a:'{"a":"a"}'}})

I get the output:

"{"a":{"a":"{\"a\":\"a\"}"}}"

And I try to deserialize by:

JSON.parse('{"a":{"a":"{\"a\":\"a\"}"}}')

I get the error:

Uncaught SyntaxError: Unexpected token a(…)

How can I deserialize the original object?

enter image description here

Upvotes: 0

Views: 874

Answers (2)

Sherali Turdiyev
Sherali Turdiyev

Reputation: 1743

Just use from variables:

var str = JSON.stringify({
  a: {
    a: '{"a":"a"}'
  }
});
console.log(str); //{"a":{"a":"{\"a\":\"a\"}"}}
console.log(JSON.parse(str));  //original object
console.log(JSON.parse('{"a":{"a":"{\"a\":\"a\"}"}}')); //error

Upvotes: 0

Jeff Tian
Jeff Tian

Reputation: 5893

OK, I got the trick...

Escape the backslash '\', this works:

JSON.parse('{"a":{"a":"{\\"a\\":\\"a\\"}"}}')

Upvotes: 2

Related Questions