我有一个这样的Json文件
{
"0":{
"poperty1":"poperty1",
"poperty2":"poperty2",
},
"1":{
"poperty1":"poperty1",
"poperty2":"poperty2",
},
"2":{
"poperty1":"poperty1",
"poperty2":"poperty2",
},
}
我用这个函数读到了它:
function readJson(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "file.json", false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status === 0)
{
// console.log(JSON.parse(rawFile.responseText));
}
}
};
rawFile.send(null);
return JSON.parse(rawFile.responseText);
}
但它返回除0以外的所有值
"1":{
"poperty1":"poperty1",
"poperty2":"poperty2",
},
"2":{
"poperty1":"poperty1",
"poperty2":"poperty2",
}
即使我删除它并从1开始执行json,它也会返回1。
知道为什么吗?
发布于 2018-06-26 06:19:38
编辑
我在github上更新了your JSON,并测试了XHR响应和解析的对象,以检查其正确性,我可以肯定地说它工作正常:
function readJson(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "https://raw.githubusercontent.com/crisz/file/master/file.json", false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status === 0)
{
console.log(JSON.parse(rawFile.responseText));
}
}
};
rawFile.send(null);
// return JSON.parse(rawFile.responseText);
}
readJson();
在前面的回答中,我没有注意到异步函数内部的返回,如果你对异步函数在Javascript中是如何工作的有疑问,你可以查看this answer。
老答案
您的JSON格式不正确。JSON specification不希望在一个集合的最后一个键值的末尾有逗号。
去掉尾随的逗号,解析就能正常工作了:
{
"0":{
"poperty1":"poperty1",
"poperty2":"poperty2"
},
"1":{
"poperty1":"poperty1",
"poperty2":"poperty2"
},
"2":{
"poperty1":"poperty1",
"poperty2":"poperty2"
}
}
如果在生成的对象中删除逗号仍然存在问题,那么请尝试测试您的API端点,看看响应是否是您所期望的。
https://stackoverflow.com/questions/51032445
复制相似问题