Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON: why are forward slashes escaped?

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?

like image 904
Jason S Avatar asked Oct 16 '09 21:10

Jason S


People also ask

Why is forward slash escaped in JSON?

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.

What should be escaped in JSON?

In JSON the only characters you must escape are \, ", and control codes. Thus in order to escape your structure, you'll need a JSON specific function.

Does JSON have escape characters?

Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing. Backspace is replaced with \b, Form feed is replaced with \f, Newline is replaced with \n, Carriage return is replaced with \r, Tab is replaced with \t, Double quote is replaced with \", Backslash is replaced with \\.


2 Answers

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, like Harold L points out:

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

Harold L answered Oct 16 '09 at 21:59

Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out:

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 answered Oct 16 '09 at 22:00 (#1580667)

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)

like image 85
Ruben Avatar answered Sep 28 '22 05:09

Ruben


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

like image 23
Harold L Avatar answered Sep 28 '22 03:09

Harold L