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?
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.