views:

842

answers:

3

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?

+2  A: 

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

Harold L
WTF? This is false. You can escape EVERY char if you want, that's true, but the JSON specs specifically says you MUST escape forward slashes. Read json.org.
Seb
I haven't read the spec but according to http://www.jsonlint.com/, {"a":"a/b/c"} is a perfectly valid JSON string.
Darin Dimitrov
json.org says 'Any UNICODE character except " or \ or control character'. You're saying / is a control character?
Harold L
No it doesn't. It explicitly says 'Any UNICODE character except " or \ or control character'. / is not mentioned as a character you must escape.
Ruben
Harold: you are indeed correct. See http://www.ietf.org/rfc/rfc4627.txt p. 4 (it would be helpful to quote the RFC in your answer)
Jason S
@Seb, no they don't. They say "Any Unicode character except " or \ or control character" is allowed.
Kinopiko
A: 

This is because HTML does not allow a string inside a <script> tag to contain </, so in case that substring's there, you should escape every forward slash.

Seb
We said the same thing, but you're better at the formatting, +1 sir
Gurdas Nijor
Thanks, Gurdas!
Seb
+4  A: 

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)

Ruben
That ASP method is yuck indeed!
meder
Thanks for the answer. Never thought of that edge case. They should escape instances of </ with <\/, but not escape all the other slashes. :/
Jason S
That would be a good thing, escaping just </. Though JSON is not often embedded in script tags anyway.
Ruben
yeah, the hoops people have gone through for HTML... this is now the 2nd recent surprise for me re: JSON. The other one was that Infinity and NaN are not serialized. http://stackoverflow.com/questions/1423081/
Jason S