Jade
Jade

Reputation: 21

How to assign json object using getJSON

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

Upvotes: 1

Views: 246

Answers (3)

maksymilians
maksymilians

Reputation: 31

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

Upvotes: 0

Abdul Rahim Shaikh
Abdul Rahim Shaikh

Reputation: 47

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

Upvotes: 0

Sagar Arora
Sagar Arora

Reputation: 1783

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

Upvotes: 1

Related Questions