简体   繁体   中英

jQuery JSON.parse exception

This will fail:

 var obj= JSON.parse('{"a": "\"aa\" vv","b": "b"}');

-> Uncaught SyntaxError: Unexpected token a in JSON at position 8 Whats the issue here? White space beteween a and v? documentations say that this should be working fine?

thx

You need to use \\\\ instead of \\

 var obj= JSON.parse('{"a": "\\\\"aa\\\\" vv","b": "b"}'); console.log(obj.a); console.log(obj.b); 

You should use double back slash \\\\ :

var obj= JSON.parse('{"a": "\\"aa\\" vv","b": "b"}');
console.log(obj);

Here is explaination of difference between \\ and \\\\ usage between simpleObject and object in form of String as argument of JSON.parse()

 var realObj= {"a": "\\"aa\\" vv","b": "b"}; // doubleQuote is escaped with single \\ so that doubleQuote becomes part of value string in key-value pair. Hence, single backwardSlash console.log("realObj.a==>"+realObj.a); console.log("realObj.b==>"+realObj.b); var objFromParsedJSON= JSON.parse('{"a": "\\\\"aa\\\\" vv","b": "b"}'); //doubleQuote is escaped with double \\\\ so that the argument of JSON.parse should also escape doubleQuote and interpret it as \\" after processing. Hence, double \\\\ console.log("objFromParsedJSON.a==>"+objFromParsedJSON.a); console.log("objFromParsedJSON.b==>"+objFromParsedJSON.b); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM