Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
480 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...