json parse error with double quotes json parse error with double quotes php php

json parse error with double quotes


Javascript unescapes its strings and json unescapes them as well.the first string ( '{"result": ["lunch", "\"Show\""] }' ) is seen by the json parser as{"result": ["lunch", ""Show""] }, because \" in javascript means ", but doesn't exit the double quoted string.

The second string '{"result": ["lunch", "\\\"Show\\\""] }' gets first unescaped to {"result": ["lunch", "\"Show\""] } (and that is correctly unescaped by json).

I think, that '{"result": ["lunch", "\\"Show\\""] }' should work too.


Well, finally, JSON's parse uses the same eval, so there's no difference when you give them smth. with incorrect syntax. In this case you have to escape correctly your quotes in php, and then escape them and their escaping slashes with json_encode

<?php    $json = '{"result": ["lunch", "\"Show\""] }';    echo json_encode($json);?>OUTPUT: "{\"result\": [\"lunch\", \"\\\"Show\\\"\"] }"

This should work on client-side JS (if I've made no typos).


This problem is caused by the two-folded string escaping mechanism: one comes from JS and one comes from JSON.

A combination of the backslash character combined with another following character is used to represent one character that is not otherwise representable within the string.''\\'' stands for '\' etc.

This escaping mechanism takes place before JSON.parse() works.

For Example,

var parsedObj = JSON.parse('{"sentence": "It is one backslash(\\\\)"}');console.log(parsedObj.sentence);>>>"It is one backslash(\)"

From the string generator's perspective, it passes four backlashes '\' into the JavaScript interpretor.

From the JavaScript interpretor's perspective, it inteprets there are two backlashes(\) as each '\\' sequence will be interpreted as one '\'.

From the JSON parser's perspective, it receives two backlashes(\\) and the JSON string escape rules will parses it as one single '\' which is the output result.

Explain you first code:

var testJson = '{"result": ["lunch", "\"Show\""] }';//The real string after sequence escaping in to JS is//'{"result": ["lunch", ""Show""] }' //which is passed into the JSON.parse.//Thus, it breaks the JSON grammar and generates an errorvar tags = JSON.parse(testJson);  alert (tags.result[1]);