JSON: why are forward slashes escaped?

2018-12-31 04:42发布

The reason for this "escapes" me.

JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a\/b\/c"} instead of {"a":"a/b/c"}.

Why?

6条回答
ら面具成の殇う
2楼-- · 2018-12-31 04:49

PHP escapes forward slashes by default which is probably why this appears so commonly. I'm not sure why, but possibly because embedding the string "</script>" inside a <script> tag is considered unsafe.

This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES flag but most developers will not use this since the original result is already valid JSON.

查看更多
闭嘴吧你
3楼-- · 2018-12-31 04:49

Since JSON is by definition javascript, and in javascript by definition a single backslash cannot be present in a string without being a part of a special encoded symbol (like newline), then it's perfectly logical to add an additional special encoded symbol for a forward slash, because this eases the task of preventing XSS attacks SO MUCH that you might even thank that genious man who managed to pull it off with including this (seemingly) controversal hack into the JSON specification. They could as well add the same special symbols for angle brackets, but there appears no need to do so because with the forward slash neutralized it's no more hostile and they can throw as many angle brackets at the code as they like - it simply won't allow any crazy-ass XSS to succeed.

查看更多
泪湿衣
4楼-- · 2018-12-31 04:54

The JSON spec says you CAN escape forward slash, but you don't have to.

查看更多
春风洒进眼中
5楼-- · 2018-12-31 04:59

Ugly PHP!

The JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES must be default, not an (strange) option... How to say it to php-developers?

The default MUST be the most frequent use, and the (current) most widely used standards as UTF8. How many PHP-code fragments in the Github or other place need this exoctic "embedded in HTML" feature?

查看更多
有味是清欢
6楼-- · 2018-12-31 05:00

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out.

Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)

查看更多
梦醉为红颜
7楼-- · 2018-12-31 05:15

I asked the same question some time ago and had to answer it myself. Here's what I came up with:

It seems, my first thought [that it comes from its JavaScript roots] was correct.

'\/' === '/' in JavaScript, and JSON 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.

查看更多
登录 后发表回答