Fill Html Table Based On JSON
I need to map the result of calling an URL into html table but I can't figure out a way to do it. The URL to be used to get data is 'https://abcdefghi/h5s5-hcxg.json'. So can anyon
Solution 1:
You're not reference the json object correctly. json[i].name should really be the key you're after eg json[i].total_capacity_certified, because there is no name key in the json file your result will appear empty. The code below loops through each json object and for every key creates a new table column
<table id="results">
<tr>
<td></td>
</tr>
</table>
.js
$.ajax({
url: "https://health.data.ny.gov/resource/h5s5-hcxg.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
// we'll put all our html in here for now
var html = '';
for (var i=0;i<json.length;++i)
{
// if on first loop, create the col headers
if(i===0){
html += '<thead><tr>';
$.each(json[i], function(key, value){
html += '<td>'+key+'</td>' ;
});
html += '</thead></tr>';
}
// loop through all the json objects and for every key add a column with the value
html += '<tr>';
$.each(json[i], function(key, value){
html += '<td>'+value+'</td>' ;
});
html += '</tr>';
}
// push all the html in one go to the page
$('#results').append(html);
}
});
Post a Comment for "Fill Html Table Based On JSON"