jeroen/jsonlite

Incoherence when json contains \\

denrou opened this issue · 1 comments

Let's take this json:

{
  "foo": "\\ bar"
}

If we save this json under foo.json and try to load it with jsonlite, everything works fine:

jsonlite::fromJSON("foo.json")
$foo
[1] "\\ bar"

However, if we try to parse the same json by giving a character string instead, it fails:

jsonlite::fromJSON('{"foo":"\\ bar"}')
Error: lexical error: inside a string, '\' occurs before a character which it may not.
                               {"foo":"\ bar"}
                     (right here) ------^

This is unrealted to jsonlite. When you enter the string '{"foo":"\\ bar"}' in the terminal, the \\ gets unescaped, and the actual string only contains a single \.

str <- '{"foo":"\\ bar"}'
cat(str, "\n")

Confusingly R re-escaped the string when you print() it but the actual string has only a single \ and hence is not valid. If you want a double backslash you need to escape both characters when you enter them:

str <-'{"foo":"\\\\ bar"}'
cat(str, "\n")
jsonlite::fromJSON(str)