Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

php - json parse error with double quotes

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...