使用JSON.parse时出现无效字符javascript错误

invalid character javascript error while using JSON.parse

本文关键字:无效 字符 javascript 错误 JSON parse 使用      更新时间:2023-09-26

我正在尝试将json字符串转换为从.js文件读取的对象格式。

以下是document.js 中的JSON字符串

    [
     {
       "type": "TableShape",
       "id": "63c0f27a-716e-804c-6873-cd99b945b63f",
       "x": 80,
       "y": 59,
       "width": 99,
       "height": 107,       
       "name": "Group",
       "entities": [
         {
           "text": "id",
           "id": "49be7d78-4dcf-38ab-3733-b4108701f1"
         },
         {
           "text": "employee_fk",
           "id": "49be7d78-4dcf-38ab-3733-b4108701fce4"
         }
       ]
     }
   ];

现在我使用AJAX调用window load中的document.js,就像下面的一样

 $(window).load(function () {
            $.ajax({
                url: "JS/Draw2d/SampleData/document.js",
                async: false,
                success: function (result) {
                    debugger;
                    jsonStringFromServer = JSON.parse(result);//Here Javascript error stating invalid character 
                    alert(jsonStringFromServer);
                }
            });           
        });

$.ajax函数接收到JSON时,它会自动为您取消序列化。您看到的错误是因为您将对象传递给JSON.parse,而不是JSON格式的字符串——您根本不需要使用JSON.parse。试试这个:

success: function (result) {
    debugger;
    console.log(result); // = the received object
}

我还强烈建议您删除async: false,因为使用它是非常糟糕的做法。