Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug with Javascript's JSON.parse?

console.log(JSON.parse('{"data":"{\"json\":\"rocks\"}"}'));

gives error (tested on Firefox and Chrome's console). Is this a bug with JSON.parse? Same decodes well when tested with PHP.

print_r(json_decode('{"data":"{\"json\":\"rocks\"}"}', true));
like image 303
kehers Avatar asked Sep 29 '12 18:09

kehers


1 Answers

This string is processed differently in PHP and JS, i.e. you get different results.

The only escapes sequences in single quoted strings in PHP are \\ and \'. All others are outputted literally, according to the documentation:

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

In JS on the other hand, if a string contains an invalid escape sequence, the backslash is discarded (CV means character value):

  • The CV of CharacterEscapeSequence :: NonEscapeCharacter is the CV of the NonEscapeCharacter.
  • The CV of NonEscapeCharacter :: SourceCharacter but not EscapeCharacter or LineTerminator is the SourceCharacter character itself.

The quote might not be helpful by itself, but if you follow the link and have a look at the grammar, it should become clear.


So in PHP the string will literally contain \" while in JS it will only contains ", which makes it invalid JSON:

{"data":"{"json":"rocks"}"}

If you want to create a literal backslash in JS, you have to escape it:

'{"data":"{\\"json\\":\\"rocks\\"}"}'
like image 164
Felix Kling Avatar answered Oct 04 '22 02:10

Felix Kling