Error with Javascript JSON.parse?

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

gives an error (tested on the Firefox and Chrome console). Is this a bug with JSON.parse? It also decodes well when testing with PHP.

 print_r(json_decode('{"data":"{\"json\":\"rocks\"}"}', true)); 
+2
source share
5 answers

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

The only sequences of screens in single quotes in PHP are \\ and \' . All the rest are displayed literally, according to the documentation :

To specify a literal single quote, execute it with a backslash ( \ ). To specify a literal backslash, double it ( \\ ). All other instances of the backslash will be treated as a literal backslash: this means that other escape sequences that you might get used to, such as \r or \n , will be issued literally, as indicated, and not have any special value.

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

  • CV CharacterEscapeSequence :: NonEscapeCharacter is a CV NonEscapeCharacter.
  • CV NonEscapeCharacter :: SourceCharacter, but not EscapeCharacter or LineTerminator - this is the SourceCharacter character itself.

The quote may not be practical on its own, but if you follow the link and look at the grammar, it should become clear.


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

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

If you want to create a literal backslash in JS, you need to avoid it:

 '{"data":"{\\"json\\":\\"rocks\\"}"}' 
+10
source

To have a literal backslash in a string literal, you need \\ .

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

This will successfully escape the internal quotes for handling JSON.

+4
source

You need to avoid backslashes:

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

You really don't need to avoid double quotes inside single quotes, and you have two extra quotes in the input around the inner object, just

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

.

+1
source

an object with a single '\' is not parsed by JSON.parser

myobj = {\ "json \": \ "rocks \"}

myobj = {\\ "json \\": \\ "rocks \\"}

Hinged lines worked for me

remove backslash

 while(typeof myobj == 'string'){ myobj = JSON.parse(myobj) } 
0
source

Source: https://habr.com/ru/post/1200737/


All Articles