我从字符串中获取json的自定义方法:
function GetJSON(a) {
if (typeof a !== "string" || !a || a == null) return null;
a = a.replace(/\r\n|\r|\n|\t/g, '').replace(/\\/g, '/');
return new Function("return " + a)();
}
var notes ='{editable:true,useAjax:false,notes:[{"top":76,"left":411,"width":30,"height":30,"text":"hill","editable":true},{"top":183,"left":556,"width":30,"height":30,"text":"lake","editable":true}]}';
return GetJSON(notes); //<-- works fine
//I am trying to replace my custom method with
return JSON.parse(notes);
但是当我调用JSON.parse()
时出现语法错误有什么不对?
编辑: 我将从调试输出传递给JSON.parse()的实际值粘贴。
答案 0 :(得分:4)
notes = "{editable:true,useAjax:false,notes:[" + notes + "]}";
你忘了在这里引用你的钥匙。它应该是:
notes = '{"editable":true,"useAjax":false,"notes":[' + notes + ']}';
最终的JSON应该是:
var notes ='{"editable":true,"useAjax":false,"notes":[{"top":76,"left":411,...'
答案 1 :(得分:2)
您的备注部分在两个,
集之间缺少{}
,使其成为无效的JSON。
应该是
[..snip..] "editable":true}, ' + '{"top":20,"left"[...snip...]
^^--- missing