简体   繁体   中英

getjson array jquery undefined

Good day, I'm trying to run a simple getJSON to get information from data json, almost done but when running, get undefined in html

Here's my jquery :

$(document).ready( function() {
  $.getJSON("/airport.json?code=bgw", function(data) {
    $('#stage').html('<p> Name: ' + data.result.request.code + '</p>');
    $.each(data.result.response.airport.pluginData.schedule.arrivals.data, function() {
      $("ul").append("<li>Name: "+this['flight.status.text']+"</li><br />");
    });
  });
});

data json :

`  {
  "result": {
    "response": {
      "airport": {
        "pluginData": {
          "schedule": {
            "arrivals": {
              "data": [
                {
                  "flight": {
                    "status": {
                      "live": true,
                      "text": "Estimated 13:44",
                      "icon": "green",
                      "estimated": null,
                      "ambiguous": false
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
}
`  

Any ideas on what I might be doing wrong?

You're accessing the nested object as this['flight.status.text'] . I believe you want to do this.flight.status.text . See the difference below

 var data = [{ test: { deep: { nested: { object: 1 } } } }, { test: { deep: { nested: { object: 2 } } } }]; console.log("Not working"); $.each(data, function() { console.log(this['test.deep.nested.object']); }); console.log("--------------"); console.log("Working"); $.each(data, function() { console.log(this.test.deep.nested.object); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

Also, as per your your JSON, data.result.request.code doesn't exist.

Use this.flight.status.text to display the text like below

  $(document).ready( function() { data={ "result": { "response": { "airport": { "pluginData": { "schedule": { "arrivals": { "data": [ { "flight": { "status": { "live": true, "text": "Estimated 13:44", "icon": "green", "estimated": null, "ambiguous": false } } } ] } } } } } } }; $('#stage').html('<p> Name: ' + 'bgw' + '</p>'); $.each(data.result.response.airport.pluginData.schedule.arrivals.data, function(){ $("ul").append("<li>Name: "+this.flight.status.text+"</li><br />"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="stage"></div> <ul></ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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