Philipp Claßen
Philipp Claßen

Reputation: 44009

Is a JSON library allowed to quote slashes?

I noticed that depending on the implementation, some JSON libraries quote / characters, others don't.

Example 1: Lua

local cjson = require 'cjson'
print(cjson.encode({ x = "/" }))
--> {"x":"\/"}

Example 2: JavaScript

console.log(JSON.stringify({ x: "/" }))
--> '{"x":"/"}'

I wonder if the quoting of Lua's cjson libray is a bug or a valid feature. If it is not, I'm concerned about base64 encoded strings that are sent over the network and should be processed by any language. I'm concerned about possibly unintended side-effects of Lua cjson when it changes strings after first decoding the JSON string and than encoding it again, for example:

local x = '{"x":"/"}'
print(x)
--> {"x":"/"}
print(cjson.encode(cjson.decode(x)))
--> {"x":"\/"}

I wonder if this is allowed. Is it still the same JSON data? I would have expected that the actual string contents should not be changed by applying a decode followed by an encode operation.

Is it allowed in JSON to quote a '/', or does it change the payload in a non standard conformant way?

From what I tested, assuming that "/" == "\/" holds is not portable over different languages. In a small sample of languages, I found mixed results. Some accept it, some don't, some accept it but issue warnings (so it is maybe not portable). Here is an overview:

+------------+-------------+----------------------------------+
|  Language  | "/" == "\/" |              Notes               |
+------------+-------------+----------------------------------+
| Lua        | true        | -                                |
| JavaScript | true        | -                                |
| C++        | true        | warning: unknown escape sequence |
| Python     | false       | -                                |
| Ruby       | true        | -                                |
+------------+-------------+----------------------------------+

Upvotes: 0

Views: 919

Answers (2)

Joe Clay
Joe Clay

Reputation: 35837

Going by the ECMA-404 spec, it should be allowed:

\/ represents the solidus character (U+002F).

The following four cases all produce the same result:

  • "\u002F"
  • "\u002f"
  • "\/"
  • "/"

Upvotes: 2

Tomalak
Tomalak

Reputation: 338336

The spec defines a string as

JSON string formal definition

So the sequence \/ is clearly allowed. But it is not necessary, since / also falls into the "Any Unicode character except " or \ or control character" range.

The "warning: unknown escape sequence" is not correct in this case.


If it is not, I'm concerned about base64 encoded strings that are sent over the network and should be processed by any language.

I'm not sure I understand. Base64 and JSON have nothing to do with each other.

Upvotes: 2

Related Questions