如何在构建 JSON 字符串时转义特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19176024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape special characters in building a JSON string?
提问by dinesh707
Here is my string
这是我的字符串
{
'user': {
'name': 'abc',
'fx': {
'message': {
'color': 'red'
},
'user': {
'color': 'blue'
}
}
},
'timestamp': '2013-10-04T08: 10: 41+0100',
'message': 'I'mABC..',
'nanotime': '19993363098581330'
}
Here the message contains single quotation mark, which is same as the quotation used in JSON. What I do is fill up a string from user inputs such as message. So, I need to escape those kind of special scenarios which breaks the code. But other than string replace, is there any way to make them escape but still allow HTML to process them back to the correct message?
此处消息包含单引号,与 JSON 中使用的引号相同。我所做的是从用户输入(例如消息)中填充一个字符串。所以,我需要避开那些破坏代码的特殊场景。但是除了字符串替换之外,有什么方法可以让它们转义但仍然允许 HTML 将它们处理回正确的消息?
回答by Mark Amery
I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.
我对关于一个基本主题的如此备受关注的问题存在高度支持的错误信息感到震惊。
JSON strings cannot be quoted with single quotes. The various versions of the spec (the originalby Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.
JSON 字符串不能用单引号引用。规范的各种版本(Douglas Crockford的原版、ECMA 版本和IETF 版本)都声明字符串必须用双引号引用。这不是一个理论问题,也不是目前公认的答案所暗示的意见问题;如果您尝试解析单引号字符串,现实世界中的任何 JSON 解析器都会出错。
Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:
Crockford 和 ECMA 的版本甚至使用漂亮的图片显示了字符串的定义,这应该可以清楚地表明这一点:


The pretty picture also lists all of the legitimate escape sequences within a JSON string:
漂亮的图片还列出了 JSON 字符串中的所有合法转义序列:
\"\\\/\b\f\n\r\t\ufollowed by four-hex-digits
\"\\\/\b\f\n\r\t\u后跟四位十六进制数字
Note that, contrary to the nonsense in some other answers here, \'is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.
请注意,与此处其他一些答案中的废话相反,\'在 JSON 字符串中永远不是有效的转义序列。它不需要,因为 JSON 字符串总是双引号。
Finally, you shouldn't normally have to think about escaping characters yourself when programaticallygenerating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.
最后,在以编程方式生成 JSON时,您通常不必考虑自己转义字符(当然,您在手动编辑,例如,基于 JSON 的配置文件时会这样做)。相反,使用您的语言具有的任何本机映射、数组、字符串、数字、布尔值和 null 类型形成您想要编码的数据结构,然后使用 JSON 编码函数将其编码为 JSON。这样的函数可能内置于您使用的任何语言中,例如 JavaScript 的JSON.stringify、PHP 的json_encode或 Python 的json.dumps. 如果您使用的语言没有内置此类功能,则可能会找到要使用的 JSON 解析和编码库。如果您只是使用语言或库函数将事物与 JSON 相互转换,您甚至永远不需要知道 JSON 的转义规则。这就是这里被误导的提问者应该做的。
回答by AlexB
A JSON string must be double-quoted, according to the specs, so you don't need to escape '.
If you have to use special character in your JSON string, you can escape it using \character.
根据规范,JSON 字符串必须用双引号引起来,因此您无需转义'。
如果您必须在 JSON 字符串中使用特殊字符,您可以使用\字符对其进行转义。
See this list of special character used in JSON :
请参阅此 JSON 中使用的特殊字符列表:
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\ Backslash character
However, even if it is totally contrary to the spec, the author could use \'.
但是,即使它完全违反规范,作者也可以使用\'.
This is badbecause :
这很糟糕,因为:
- It IS contrary to the specs
- It is no-longer JSON valid string
- 它与规格相反
- 它不再是 JSON 有效字符串
But it works, as you want it or not.
但它可以工作,无论您是否愿意。
For new readers, always use a double quotes for your json strings.
对于新读者,请始终对 json 字符串使用双引号。
回答by David Knipe
Everyone is talking about how to escape 'in a '-quoted string literal. There's a much bigger issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use ".
每个人都在谈论如何'在带'引号的字符串文字中转义。这里有一个更大的问题:单引号字符串文字不是有效的 JSON。JSON 基于 JavaScript,但它不是一回事。如果您在 JavaScript 代码中编写对象字面量,那很好;如果您确实需要 JSON,则需要使用".
With double-quoted strings, you won't need to escape the '. (And if you did want a literal "in the string, you'd use \".)
使用双引号字符串,您无需转义'. (如果您确实想要"字符串中的文字,则可以使用\".)
回答by Kickass
Most of these answers either does not answer the question or is unnecessarily long in the explanation.
这些答案中的大多数要么没有回答问题,要么在解释中不必要地冗长。
OK so JSON only uses double quotation marks, we get that!
好的,所以 JSON 只使用双引号,我们明白了!
I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:
我试图使用 JQuery AJAX 将 JSON 数据发布到服务器,然后返回相同的信息。我发现的已发布问题的最佳解决方案是使用:
var d = {
name: 'whatever',
address: 'whatever',
DOB: '01/01/2001'
}
$.ajax({
type: "POST",
url: 'some/url',
dataType: 'json',
data: JSON.stringify(d),
...
}
This will escape the characters for you.
这将为您转义字符。
This was also suggested by Mark Amery, Great answer BTW
这也是 Mark Amery 提出的,很好的答案 BTW
Hope this helps someone.
希望这可以帮助某人。
回答by Luigi D'Amico
The answer the direct question:
To be safe, replace the required character with \u+4-digit-hex-value
回答直接问题:
为了安全起见,用 \u+4-digit-hex-value 替换所需的字符
Example:
If you want to escape the apostrophe ' replace with \u0027
D'Amico becomes D\u0027Amico
示例:如果要转义撇号 ' 替换为
\u0027 D'Amico 变为 D\u0027Amico
NICE REFERENCE: http://es5.github.io/x7.html#x7.8.4
不错的参考:http: //es5.github.io/x7.html#x7.8.4
回答by Sanju Kaniyamattam
Use encodeURIComponent() to encode the string.
使用 encodeURIComponent() 对字符串进行编码。
Eg. var product_list = encodeURIComponent(JSON.stringify(product_list));
例如。var product_list = encodeURIComponent(JSON.stringify(product_list));
You don't need to decode it since the web server automatically do the same.
您不需要解码它,因为 Web 服务器会自动执行相同的操作。
回答by YankTHEcode
May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..
可能是我参加聚会为时已晚,但这将解析/转义单引号(不想参与解析与转义的战斗)..
JSON.parse("\"'\"")
回答by Tom Blitz
I think we all agree single quoted jsons aren't real jsons. Be that as it may, we still need to address the question of escaping " within a double quoted json string, in the absence of libraries to do so for us.
我想我们都同意单引号 jsons 不是真正的 jsons。尽管如此,我们仍然需要解决在双引号 json 字符串中转义 " 的问题,因为没有库为我们这样做。
Replacing each " with a \" is NOT ENOUGH: User may enter the input: \ and parsing, again, fails (think why).
用 \ 替换每个 " 还不够: 用户可以输入输入: \ 并再次解析失败(想想为什么)。
Instead, first replace each \ with \ (double backslash). Only then, replace each " with \" (backslash followed by ").
相反,首先将每个 \ 替换为 \(双反斜杠)。然后,将每个“替换为\”(反斜杠后跟“)。
回答by 4T2G
To allow single quotes within doubule quoted string for the purpose of json, you double the single quote. {"X": "What's the question"} ==> {"X": "What''s the question"}
为了 json 的目的,为了在双引号字符串中允许单引号,您可以将单引号加倍。{“X”:“问题是什么”} ==> {“X”:“问题是什么”}
https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes
https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes
The \' sequence is invalid.
\' 序列无效。
回答by Bart
regarding AlexB's post:
关于 AlexB 的帖子:
\' Apostrophe or single quote
\" Double quote
escaping single quotes is only valid in single quoted json strings
escaping double quotes is only valid in double quoted json strings
转义单引号仅在单引号 json 字符串中
有效 转义双引号仅在双引号 json 字符串中有效
example:
例子:
'Bart\'s car' -> valid
'Bart says \"Hi\"' -> invalid

