开发者

Why is the slash an escapable character in JSON? [duplicate]

This question already has answers here: 开发者_开发技巧 JSON: why are forward slashes escaped? (5 answers) Closed 3 months ago.

json.org states, that forward slashes (aka solidus, /) can be escaped:

"\/"

However, unescaped slashes are valid, too:

"/"

What's the rational behind this? Does it come from the Javascript roots? (I.e., "</script>" is a problem in browser-based Javascript, see Douglas Crockford's comment) Or has it any other reason?


It seems, my first thought was correct.

'\/' === '/' in JavaScript, and JSON almost is valid JavaScript. However, why are the other ignored escapes (like \z) not allowed in JSON?

The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.


I've just published a review of this issue on my blog. I think you are right, that's the only reason. Also note that the slash is the only standard character allowed to be escaped.

Usually JSON encoders do it wrong and escape any slash they find along the way, while only the slash in </script> should be escaped, and maybe all the ones matched by the JavaScript RegExp /<\/\w+/, for the same reason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜