【问题标题】:JavaScript - Read Json if first value if is ZeroJavaScript - 如果第一个值为零,则读取 Json
【发布时间】:2018-06-25 22:09:45
【问题描述】:

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

知道为什么吗?

【问题讨论】:

  • 您发布的 JSON 中没有 0 值。请edit您的问题并附上实际结果。也记录没有 JSON 解析的结果。
  • 另外你必须等待请求完成。

标签: javascript json ajax xmlhttprequest


【解决方案1】:

编辑

我在 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 端点以查看响应是否符合您的预期。

【讨论】:

  • 我明白了。但是在我的代码中,我有更多的对象,我删除了一些对象,以免问题太长。所以我的“真实”Json 是有效的。
猜你喜欢
  • 1970-01-01
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多