2

Suppose I have an object variable:

var obj = { key: '\"Hello World\"' } 

Then I tried parse it to string by using JSON.stringify in Chrome devtools console:

JSON.stringify(obj) // "{"key":"\"Hello World\""}" 

I get the result "{"key":"\"Hello World\""}". Then I give it to a string

var str = '{"key":"\"Hello World\""}' 

At least I try to convert it back to obj:

JSON.parse(str); 

but the browser tell me wrong Uncaught SyntaxError

What confused me is why this is wrong? I get the string from an origin object and I just want turn it back.

How can I fix this problem? If I want do the job like convert obj to string and return it back, how can I do?

2
  • You might find what you're doing easier if you don't use \ to escape characters in this case. If you alternate between ' and " you don't need to escape. For example, you can do key: '"Hello World"'. Commented Dec 23, 2015 at 15:34
  • A string value is not the same as a string literal. JSON.parse(JSON.stringify(obj)) will work just fine. Commented Dec 23, 2015 at 15:37

2 Answers 2

5

You're tried to convert your JSON into a string literal by wrapping it in ' characters, but \ characters have special meaning inside JavaScript string literals and \" gets converted to " by the JavaScript parser before it reaches the JSON parser.

You need to escape the \ characters too.

var str = '{"key":"\\"Hello World\\""}' 

That said, in general, it is better to not try to embed JSON in JavaScript string literals only to parse them with JSON.parse in the first place. JSON syntax is a subset of JavaScript so you can use it directly.

var result = {"key":"\"Hello World\""}; 
Sign up to request clarification or add additional context in comments.

Comments

0

try:

var str = '{"key":"\\"Hello World\\""}'; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.