简体   繁体   English

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

[英]invalid character javascript error while using JSON.parse

I am trying to convert a json string to object format read from a .js file. 我正在尝试将json字符串转换为从.js文件读取的对象格式。

Below is the JSON string in document.js 以下是document.jsJSON字符串

    [
     {
       "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"
         }
       ]
     }
   ];

now i am calling the document.js in window load using AJAX like below 现在我正在使用如下所示的AJAXwindow 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);
                }
            });           
        });

When the $.ajax function receives JSON, it automatically deserialises it for you. $.ajax函数接收JSON时,会自动为您反序列化。 The error you're seeing is being cause because you're passing an object to JSON.parse , not a JSON formatted string - you don't need to use JSON.parse at all. 您看到的错误是由于您将对象传递给JSON.parse而不是JSON格式的字符串引起的-您根本不需要使用JSON.parse Try this: 尝试这个:

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

I would also strongly suggest you remove async: false as it is extremely bad practice to use it. 我也强烈建议您删除async: false因为使用它是极差的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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