JSON to HTML table
Mapping JavaScript Object or JSON to an HTML table.
by Subigya Panta
HTML
<pre>
Data format is,
var data = {
title : [ 'SN', 'Firstname', 'Lastname' ],
body:[
{SN : 1, Firstname: 'Subigya', Lastname: 'Panta' },
{SN : 2, Firstname: 'Alex', Lastname: 'Laiho' },
{SN : 3, Firstname: 'James', Lastname: 'Hetfield' },
{SN : 4, Firstname: 'Christian', Lastname: 'Bale' }
]
};
</pre>
<p>HTML table is</p>
<div id="table-container"></div>
JavaScript
var data = {
title : [ 'SN', 'Firstname', 'Lastname' ],
body:[
{SN : 1, Firstname: 'Subigya', Lastname: 'Panta' },
{SN : 2, Firstname: 'Alex', Lastname: 'Laiho' },
{SN : 3, Firstname: 'James', Lastname: 'Hetfield' },
{SN : 4, Firstname: 'Christian', Lastname: 'Bale' }
]
};
function createTable( data, id, newTable ){
if ( newTable ) {
var table = document.createElement( 'table' );
table.setAttribute( 'id', id );
}
else{
var table = document.getElementById( id );
}
var tableHead = table.createTHead();
var titleRow = tableHead.insertRow( 0 );
// insert title in head
var size = data.title.length;
for (var i = 0; i < size; i++) {
var cell = titleRow.insertCell( i );
cell.innerHTML = data.title[i];
}
// insert body
var rows = data.body.length;
var tBody = document.createElement( 'tbody' );
for (var i = 0; i < rows; i++ ){
var bodyRow = tBody.insertRow( i );
for ( var j = 0; j < size; j++) {
var cell = bodyRow.insertCell( j );
console.log( data.title[j] );
cell.innerHTML = data.body[i][data.title[j]];
}
}
table.appendChild( tBody );
return table;
}
var tableContainer = document.getElementById( 'table-container' );
tableContainer.appendChild( createTable( data, 'json-table', true ) );