jsonToHtmlTable(jsonObj, '#records');
HTML に続いて呼び出す(例: ドキュメントの準備ができている場合)
HTML
<table id="records">
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
JavaScript
//Sample JSON Object (array of json objects)
var jsonObj = [{"a":1,"b":3,"ds":4},{"a":2,"b":5,"ds":4}];
//Use
$(document).ready(function(){
jsonToHtmlTable(jsonObj, '#records');
});
//implementation
function jsonToHtmlTable(jsonObj, selector) {
addColumns(jsonObj, selector);
addRows(jsonObj, selector);
}
function addColumns(jsonObj, selector) {
if (!$.isArray(jsonObj) || jsonObj.length < 1)
return;
var object = jsonObj[0];
var theadHtml = "";
for (var property in object) {
if (object.hasOwnProperty(property))
theadHtml += "<th>" + property + "</th>";
}
$(selector + ' thead tr').html(theadHtml);
}
function addRows(jsonObj, selector) {
var tbody = $(selector + ' tbody');
$.each(jsonObj, function (i, d) {
var row = '<tr>';
$.each(d, function (j, e) {
row += '<td>' + e + '</td>';
});
row += '</tr>';
tbody.append(row);
});
}