这是我的绳子
{
'user': {
'name': 'abc',
'fx': {
'message': {
'color': 'red'
},
'user': {
'color': 'blue'
}
}
},
'timestamp': '2013-10-04T08: 10: 41+0100',
'message': 'I'mABC..',
'nanotime': '19993363098581330'
}
这里的消息包含单引号,这与JSON中使用的引号相同。我所做的是从用户输入(如message)填充字符串。我需要转义那些会破坏代码的特殊场景。但是除了字符串替换之外,有没有办法让它们转义,但仍然允许HTML将它们处理回正确的消息?
对于这样一个被高度关注的基本话题,出现了高度赞的错误信息,我感到震惊。
JSON字符串不能用单引号引用。该规范的各种版本(Douglas Crockford的原始版本、ECMA版本和IETF版本)都规定字符串必须用双引号括起来。这不是一个理论问题,也不是目前公认答案所暗示的意见问题;如果您试图让它解析单引号字符串,那么现实世界中的任何JSON解析器都会出错。
Crockford和ECMA的版本甚至用漂亮的图片显示了字符串的定义,这应该清楚地说明了这一点:
这张漂亮的图片还列出了JSON字符串中的所有合法转义序列:
\”
\\
\ /
\ b
\ f
\ n
r \
\ t
\u后面跟着四位十六进制数字
请注意,与这里其他一些无意义的回答相反,\'在JSON字符串中从来都不是有效的转义序列。它不需要这样,因为JSON字符串总是双引号。
Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating 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只使用双引号,我们明白了!
我试图使用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),
...
}
这将为您转义字符。
Mark Amery也提出了这个建议,顺便说一句,回答得很好
希望这能帮助到一些人。