简体   繁体   中英

How do JSON.parse() and escape characters work in JavaScript?

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?

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\""};

尝试:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM