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));
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:In JS on the other hand, if a string contains an invalid escape sequence, the backslash is discarded (
CVmeans character value):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:If you want to create a literal backslash in JS, you have to escape it: