简体   繁体   English

JSON.parse()和转义符在JavaScript中如何工作?

[英]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: 然后,我尝试在Chrome devtools控制台中使用JSON.stringify其解析为字符串:

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

I get the result "{"key":"\\"Hello World\\""}" . 我得到结果"{"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: 至少我尝试将其转换回obj:

JSON.parse(str);

but the browser tell me wrong Uncaught SyntaxError 但是浏览器告诉我错误的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? 如果我想执行将obj转换为字符串并将其返回的工作,该怎么办?

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. 您试图通过将其用'字符包装来将JSON转换为字符串文字,但是\\字符在JavaScript字符串文字中具有特殊含义,并且JavaScript解析器将\\"在到达JSON解析器之前转换为"

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.parse解析为JavaScript字符串文字来嵌入JSON。 JSON syntax is a subset of JavaScript so you can use it directly. JSON语法是JavaScript的子集,因此您可以直接使用它。

var result = {"key":"\"Hello World\""};

尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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