博士tl;
如果你在javascript/python/等等。,使用原始字符串(python的r”或javascript的String)。生的或类似的)。它们使编写JSON字符串变得更容易,因为它们避免了多个转义序列处理。
console.log(JSON.parse(String.raw`"This is a double quote >> \" <<"`))
// => This is a double quote >> " <<
更深入
在代码中编写JSON字符串时,由于字符串转义序列被多次处理而导致一些混乱。一次是在编程语言中,一次是在JSON解析器中(例如Javascript中的JSON.parse(),或类似的)
使用该语言的print函数查看编程语言中发生了哪些转义
在编程语言repl中如何显示字符串可能会令人困惑。
例如,当你直接在javascript repl中输入一个字符串时,它会以这种方式显示
'Two newlines:\n\nTab here >>\t<<\n\nBackslash here >>\\<<'
// => 'Two newlines:\n\nTab here >>\t<<\n\nBackslash here >>\\<<'
但是当您console.log()该字符串时,它会以这种方式显示它
console.log('Two newlines:\n\nTab here >>\t<<\n\nBackslash here >>\\<<')
/* =>
Two newlines:
Tab here >> <<
Backslash here >>\<<
*/
当javascript遇到字符串时,它会在将其传递给函数之前“计算”转义序列,例如,它会将每个\n替换为换行符,将每个\t替换为制表符,等等。
因此,console.log()字符串有助于更好地了解发生了什么。
如何在javascript中编码JSON中的单引号
要在javascript中编写“To a JSON”,您可以使用
console.log(JSON.parse('"This is a double quote >> \\" <<"'));
// => This is a double quote >> " <<
在python和其他语言中也是类似的。
循序渐进:
javascript evaluates the string using escape sequence rules from the javascript spec, replacing \n with a newline char, \t with a tab char, etc.
In our case, it replaces \\ with \.
The result string is "This is a double quote >> \" <<"
We put the outer double quotes to make it a valid JSON string
javascript takes the result and passes it to the JSON.parse() fn.
JSON.parse evaluates the string using escape sequence rules from the JSON standard, replacing \n with a newline char, \t with a tab char, etc. In our case,
the first character it sees is ", so it knows this is a JSON string.
Inside the JSON string, it sees \". Normally " would end the JSON string, but because " is escaped with \, it knows this isn't the end of the string and to replace \" with a literal double quote character.
the last character it sees is ", so it knows this is the end of the JSON string
The result parsed string is This is a double quote >> " <<. Note the outer double quotes are gone also.
原始字符串使事情变得更容易
Javascript的字符串。原始模板函数和python的r”字符串不做任何转义序列求值,因此它使它更容易理解,也更容易理解
console.log(JSON.parse(String.raw`"This is a double quote >> \" <<"`))
// => This is a double quote >> " <<