简体   繁体   English

如何使用 getJSON 分配 json object

[英]How to assign json object using getJSON

I want to assign a json object branch lat and lng to a jsonData variable.我想将 json object branch latlng分配给jsonData变量。
If I console.log jsonData.responseJSON.positions.length or jsonData.responseJSON.positions[0].lat , etc如果我 console.log jsonData.responseJSON.positions.lengthjsonData.responseJSON.positions[0].lat
I can see my json data well like this.我可以像这样看到我的 json 数据。 console image控制台图像
But if I code it and run, it has an error.但是,如果我对其进行编码并运行,则会出现错误。
For example,例如,

var jsonData = $.getJSON("{% static "kia_data_brlatlng.json" %}", function(data){
    console.log(jsonData)
});

for(var i = 0; i < jsonData.responseJSON.positions.length; i++) {
    //not work
}

for(var i = 0; i < 681; i++) {
    //work
}

Someone gave me a tip that it needs a callback function inside the $.getJSON but still hard to find the solution.有人给了我一个提示,它需要在$.getJSON但仍然很难找到解决方案。
Any help would be appreciated!任何帮助,将不胜感激!

I'll add how my json file looks like.我将添加我的 json 文件的外观。

{
    "positions": [
      {
        "branch": "A",
        "lat": 37.5221642,
        "lng": 127.0339206
      },
      {
        "branch": "B",
        "lat": 35.1547587,
        "lng": 129.0389295
      },
      //and 679 more
    ]
}

This is due to the async nature of Javascript.这是由于 Javascript 的异步特性。 You have to wait until you got the response.你必须等到你得到回应。 Or you can write you code when response came.或者您可以在响应到来时编写代码。

var jsonData = $.getJSON("{% static "kia_data_brlatlng.json" %}", function(data){
    console.log(jsonData)
    for(var i = 0; i < data.responseJSON.positions.length; i++) {
      //here this will work
    }
});

Or getJSON return promises so you have use then to get the response.或者 getJSON 返回承诺,这样您就可以使用 then 来获取响应。 Check it here: function wait with return until $.getJSON is finished在这里检查: function 等待返回,直到 $.getJSON 完成

After looking into your json object basically looks like this查看您的 json object 后,基本上看起来像这样

    jsonData = {
        "positions": [
          {
            "branch": "A",
            "lat": 37.5221642,
            "lng": 127.0339206
          },
          {
            "branch": "B",
            "lat": 35.1547587,
            "lng": 129.0389295
          },
          //and 679 more
        ]
    }

So if that's the case when you want to iterate it you can simply iterate it like this因此,如果您想对其进行迭代,则可以像这样简单地迭代它

    for(var i = 0; i < jsonData.positions.length; i++) {
        //work
        console.log(jsonData.positions[i])
    }

This is because getJSON function is asynchronous, so the loop is executed before you get the data in jsonData variable.这是因为 getJSON function 是异步的,所以在获取 jsonData 变量中的数据之前执行循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM