Domanda

I'm trying to receive data from JSON via AJAX, but the JSON structure is more complex rather than just one value/key.

Here's the code I'm stuck:

$.ajax('data.json', {
    crossDomain: true,
    dataType: "json",
    success: function(data, text, xhqr) {
      $.each(data, function(i, item) {
      console.log(data.Cars);
      $("body").html(data.Cars)
    });
 }
});

JSON:

{
   "extracted" : "2014-03-18 13:00:12",
   "LastRun" : "2014-03-18 13:00:00",
   "Cars" : {
      "Audi" : {
         "Total" : "18",
         "Type" : "Sport",
         "features" : {
            "Airbag" : "yes",
            "Radio" : "No",
            "Convertible" : "yes"
         }
      },
      "Ford" : {
         "Total" : "109",
         "Type" : "Sport",
         "features" : {
            "Airbag" : "yes",
            "Radio" : "No",
            "Convertible" : "no"
         }
      },
      "Mercedes" : {
         "Total" : "60",
         "Type" : "Luxury",
         "features" : {
            "Airbag" : "No",
            "Radio" : "Yes",
            "Convertible" : "yes"
         }
      }
   }
}

Ideally, I'd like the data to be displayed in this table format: enter image description here

Can someone help me please how to receive or read the json values/keys? Many thanks

È stato utile?

Soluzione

$.ajax({
    url: 'data.json',
    crossDomain: true,
    dataType: "json"
}).done(function(data) {
    var table = $('<table />'),
        thead = $('<thead />'),
        tbody = $('<tbody />');

    thead.append(
        $('<tr />').append(
            $('<th />', {text: 'Car'}),
            $('<th />', {text: 'Type'}),
            $('<th />', {text: 'Airbag'}),
            $('<th />', {text: 'Radio'}),
            $('<th />', {text: 'Convertible'}),
            $('<th />', {text: 'Total'})
        )
    );

    $.each(data.Cars, function(car, specs) {
        tbody.append(
            $('<tr />').append(
                $('<td />', {text: car}),
                $('<td />', {text: specs.Type}),
                $('<td />', {text: specs.features.Airbag}),
                $('<td />', {text: specs.features.Radio}),
                $('<td />', {text: specs.features.Convertible}),
                $('<td />', {text: specs.Total})
            )
        );
    });

    $('body').append( table.append(thead, tbody) );
});

FIDDLE

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top