kehers
kehers

Reputation: 4160

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));

Upvotes: 6

Views: 12154

Answers (5)

Sandeep P
Sandeep P

Reputation: 4411

object with one or more then '\' wont return Object by JSON.parser, It will return the string again with skipping one '\'. You can do parse again and again until all '\' skipped.

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

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

Following lines worked for me

remove backslash

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

Upvotes: 2

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

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

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

is enough.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816374

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\\"}"}'

Upvotes: 12

jonvuri
jonvuri

Reputation: 5920

You need to escape the backslashes:

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

Upvotes: 3

I Hate Lazy
I Hate Lazy

Reputation: 48761

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

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

This will successfully escape the inner quotation marks for the JSON processing.

Upvotes: 4

Related Questions