Javascript JSON.Parse方法在清理JSON数据时失败-语法错误意外标记
我有一个包含json节点的js文件。这个文件被读入我的程序,变成一个字符串,然后我在上面运行JSON.parse:Javascript JSON.Parse方法在清理JSON数据时失败-语法错误意外标记,javascript,json,parsing,Javascript,Json,Parsing,我有一个包含json节点的js文件。这个文件被读入我的程序,变成一个字符串,然后我在上面运行JSON.parse: var client = new XMLHttpRequest(); client.open('GET', 'data/data.js'); //when the file has been loaded, this will execute client.onreadystatechange = function() { if(client.responseText
var client = new XMLHttpRequest();
client.open('GET', 'data/data.js');
//when the file has been loaded, this will execute
client.onreadystatechange = function()
{
if(client.responseText != "")
{
ScanText(client.responseText);
}
}
function ScanText(text)
{
var json;
try
{
var cleanedText = text;
cleanedText = cleanedText.replace('Var', '');
cleanedText = cleanedText.replace('arrayName', '');
cleanedText = cleanedText.replace('=','')
alert(cleanedText);
json = JSON.parse(cleanedText); //Issue happens here
alert('try');
}
catch (ex)
{
alert(ex);
}
}
我的数据文件看起来像:
[
{
AollName:'YUI678',
Contract:'123-33'
},
{
TollName:'YUI678',
Contract:'123-33'
}
]
我得到了错误“Syntax error:Unexpected token A”,它来自第一个节点AollName
为什么json.parse方法不能在此输入上运行?您的文件不包含有效的 JSON键必须加引号,字符串值必须使用双引号。仅仅因为它可以作为有效的JavaScript对象执行,并不意味着它是有效的JSON(数据交换格式)
将是有效的。您使用的JSON无效。字符串需要用双引号括起来:
[
{
"AollName": "YUI678",
"Contract": "123-33"
},
{
"TollName": "YUI678",
"Contract": "123-33"
}
]
添加到您的工作流程中
[
{
"AollName": "YUI678",
"Contract": "123-33"
},
{
"TollName": "YUI678",
"Contract": "123-33"
}
]