1

I want to assign a json object branch lat and lng to a jsonData variable.
If I console.log jsonData.responseJSON.positions.length or jsonData.responseJSON.positions[0].lat, etc
I can see my json data well like this. 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.
Any help would be appreciated!

I'll add how my json file looks like.

{
    "positions": [
      {
        "branch": "A",
        "lat": 37.5221642,
        "lng": 127.0339206
      },
      {
        "branch": "B",
        "lat": 35.1547587,
        "lng": 129.0389295
      },
      //and 679 more
    ]
}
Jade
  • 21
  • 4
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Adam Azad Aug 14 '20 at 09:10

3 Answers3

1

This is due to the async nature of 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. Check it here: function wait with return until $.getJSON is finished

Sagar Arora
  • 1,743
  • 1
  • 10
  • 19
  • I got an error to this but solved just changing `i < data.responseJSON....` to `i < jsonData.response......` Thanks! – Jade Aug 14 '20 at 09:21
0

After looking into your json object basically looks like this

    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])
    }
0

This is because getJSON function is asynchronous, so the loop is executed before you get the data in jsonData variable.