28

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Boldewyn
  • 81,211
  • 44
  • 156
  • 212
  • It does indeed have its roots in the `` tag. You can see Douglas Crockford, the originator of the JSON specifications, present the rationale for it [here](https://youtu.be/-C-JoyNuQJs?t=386). – Oliver Sieweke Nov 09 '20 at 14:08

2 Answers2

10

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.

Boldewyn
  • 81,211
  • 44
  • 156
  • 212
  • Things like \b is used for backspace in JSON, allowing \z for z would make things confusing. – remmy Nov 07 '13 at 14:39
5

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
aercolino
  • 2,193
  • 1
  • 22
  • 20
  • Hm, interesting. But you, too, don't happen to know the source for the assumption? – Boldewyn Jan 01 '11 at 19:31
  • "Also note that the slash is the only standard character allowed to be escaped." < Wrong. All characters can be escaped, some just through other methods. – remmy Nov 07 '13 at 14:36
  • 1
    I think I prefer JSON encoders who do it "wrong", because that makes things more consistent. – Johannes Riecken Jun 27 '20 at 16:09