【问题标题】:How to load a local JSON file?如何加载本地 JSON 文件?
【发布时间】:2017-05-08 01:05:51
【问题描述】:

我正在尝试通过 jquery 加载本地 JSON 文件。代码工作正常,但数组中的数据不可用。

$.getJSON("/ajax/data/myjasonfile.json", function(json) {
        console.log(json);
    });

我的控制台只显示

Object {data: Array[1]}

我的示例 json

{
    "data": [
        {
            "number": "1234",
            "nameOne": "Laten Thamn",
            "type": "Fishing Vessels",
            "flagName": "5467",
            "buildDate":"12/08/2016"
        }
    ]
}

【问题讨论】:

  • “数组中的数据不可用”是什么意思?
  • 你的意思是客户端机器本地的吗?如果是这样,这是不可能的。如果您的意思是服务器本地,那么假设您的路径有效,那么您所拥有的应该可以正常工作。
  • 数据应该作为对象可用。你的控制台说什么
  • 但我在 json 中有超过 100 条记录
  • 你应该检查数据库查询。

标签: javascript jquery arrays json ajax


【解决方案1】:

jQuery.getJSON() 使用 GET HTTP 请求从服务器加载 JSON 编码的数据。

当您在 JSON 结构中发布时,您可以通过调用 json.data 来访问该数组:

$.getJSON("/ajax/data/myjasonfile.json", function(json) {
     console.log(json.data); // Logs your array
});

【讨论】:

  • 如果它显示Object {data: Array1}它已经是一个对象
【解决方案2】:

你可以试试这个:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

我认为,在您调用 json 文件的路径中存在一些问题。您需要再次检查路径。

您可以查看此链接:Loading local JSON file

【讨论】:

  • 你应该按照上面的链接。它会帮助你。
  • 所以你说这是重复的?
【解决方案3】:

试试这个以了解您的响应结构。

 $.getJSON("myjasonfile.json", function(json) {
        console.log(json); // access the response object
        console.log(json.data); // access the array
        console.log(json.data[0]); // access the first object of the array
        console.log(json.data[0].number); // access the first object proprty of the array
    });

【讨论】:

  • 很高兴为您提供帮助 :)
【解决方案4】:

将json数据存储在数组中:

 $.getJSON("/ajax/data/myjasonfile.json", function(Data) {
        var array=[];
    for(var i=1;i<Data.length;i++)
    {
        var b=Data[i];
        var c=[];
        c.push(b.number);
        c.push(b.nameOne);
        c.push(b.type);
        c.push(b.flagName);
        c.push(b.buildDate);
        array.push(c);
    }
        console.log(array);
    });

【讨论】:

  • 我可以建议您添加一些上下文来解释您的答案吗?
  • 感谢您提供此代码 sn-p,它可能会提供一些即时帮助。一个正确的解释would greatly improve 其教育价值通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有类似但不相同的问题的读者更有用。请edit您的答案添加解释,并说明适用的限制和假设。
猜你喜欢
  • 2012-06-01
  • 2011-11-12
  • 1970-01-01
  • 2012-09-12
  • 2012-05-16
  • 2011-04-23
  • 2020-04-29
  • 1970-01-01
相关资源
最近更新 更多