将字符串转换为JSON对象会引发意外的令牌

时间:2014-09-18 09:12:39

标签: javascript json

我正在尝试将带有转义字符的字符串转换为JSON,但会收到错误

  var str = '[{"name":"content","readonly":false,"value":"<div class=\"blueheading\"><h2>Free Gifts for Him</h2><h3><a href=\"http://abcd.com/free-gifts-with-purchase-for-him.aspx\">View all for Him</a></h3></div>"},{"name":"cached","readonly":true,"value":true}]';
            var myObj = JSON.parse(str);

1 个答案:

答案 0 :(得分:5)

如果您希望在字符串文字中包含\",则必须转义\'\\"'

这给出了:

var str = '[{"name":"content","readonly":false,"value":"<div class=\\"blueheading\\"><h2>Free Gifts for Him</h2><h3><a href=\\"http://abcd.com/free-gifts-with-purchase-for-him.aspx\\">View all for Him</a></h3></div>"},{"name":"cached","readonly":true,"value":true}]';
var myObj = JSON.parse(str);

Read more about special characters in string literals