A double quote even if escaped is throwing parse error.
look at the code below
//parse the json in javascript
var testJson = '{"result": ["lunch", "\"Show\""] }';
var tags = JSON.parse(testJson);
alert (tags.result[1]);
This is throwing parse error because of the double quotes (which are already escaped).
Even eval()
won't work here.
But if i escape it with double slashes like this:
var result = '{"result": ["lunch", "\\"Show\\""] }';
var tags = JSON.parse(result);
alert (tags.result[1]);
then it works fine.
Why do we need to use double slash here in javascript?
The problem is that PHP json_encode()
function escapes a double quote with a single slash (like this: \"show\"
) which JSON.parse
won't be able to parse. How do i handle this situation?
From the docs
json_encode() takes two args, the value and options. So try
I haven't tried this though.
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.Turn off
magic_quotes_gpc
in php.ini.php to javascript Object (php >= 5.3.0)
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,
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:
If the standard C escapes are added, then
JSON.parse
will convert sequences like\"
into"
,\\
into\
,\n
into a line-feed, etc.In our project's case:
original string
""{\"lat\":28.4594965,\"lng\":77.0266383}""
After passing to
JSON.parse()
On 2nd pass to
JSON.parse()
Notice that
JSON.parse()
removed escaping characters instead of convertingstring
toobject
.After the escaping characters were removed, the string to object conversion worked.
Here is the demo: