首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript -如果第一个值为零,则读取Json

JavaScript -如果第一个值为零,则读取Json
EN

Stack Overflow用户
提问于 2018-06-26 06:09:45
回答 1查看 67关注 0票数 1

我有一个这样的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。

知道为什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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端点,看看响应是否是您所期望的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51032445

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档