使用JSON.parse时出现无效字符javascript错误
我正在尝试将使用JSON.parse时出现无效字符javascript错误,javascript,jquery,html,json,Javascript,Jquery,Html,Json,我正在尝试将json字符串转换为从.js文件读取的对象格式 下面是document.jsJSON中的JSON字符串 [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, "y": 59, "width": 99, "height": 107, "name": "
json
字符串转换为从.js
文件读取的对象格式
下面是document.js
JSON中的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
调用windowload
中的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
,因为使用它是非常糟糕的做法。尝试删除
在document.js
中JSON字符串的末尾,您可以使用此站点验证解决问题的JSON。tq另外,结果
仅在返回正确的内容类型
标题时才会自动反序列化。否则,您需要将数据类型:json
参数添加到$.ajax()
。感谢您的建议,我将遵循此建议,我真的想知道是否有任何方法可以将一些json文本写入.txt文件?