4

我从字符串中获取 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() 的实际值。

4

2 回答 2

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,...'
于 2012-04-05T17:28:23.917 回答
2

您的注释部分,在两组之间缺少 a {},使其无效 JSON。

它应该是

[..snip..] "editable":true}, ' + '{"top":20,"left"[...snip...]
                           ^^--- missing
于 2012-04-05T17:21:55.737 回答