Convert JSON data to HTML table using jQuery
by Leonardo Trimarchi
CSS
table.blueTable {
border: 1px solid #1C6EA4;
background-color: #EEEEEE;
width: 100%;
text-align: left;
border-collapse: collapse;
}
table.blueTable td, table.blueTable th {
border: 1px solid #AAAAAA;
padding: 4px 0px;
}
table.blueTable tbody td {
font-size: 13px;
}
table.blueTable tr:nth-child(even) {
background: #D0E4F5;
}
table.blueTable thead {
background: #1C6EA4;
background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
border-bottom: 2px solid #444444;
}
table.blueTable thead th {
font-size: 15px;
font-weight: bold;
color: #FFFFFF;
border-left: 2px solid #D0E4F5;
}
table.blueTable thead th:first-child {
border-left: none;
}
table.blueTable tfoot td {
font-size: 14px;
}
table.blueTable tfoot .links {
text-align: right;
}
table.blueTable tfoot .links a{
display: inline-block;
background: #1C6EA4;
color: #FFFFFF;
padding: 2px 8px;
border-radius: 5px;
}
JavaScript
var jData = '[{"Pro":"James Studer", "12/21 AM":"A", "12/21 PM":"NA","12/22 AM":"FULL", "12/22 PM":"DAY","12/23 AM":"NA", "12/23 PM":"A","12/24 AM":"A", "12/24 PM":"NA","12/25 AM":"FULL", "12/25 PM":"DAY","12/26 AM":"NA", "12/26 PM":"A","12/27 AM":"FULL", "12/27 PM":"DAY"},' +
'{"Pro":"Heather DeAcosta", "12/21 AM":"FULL", "12/21 PM":"DAY","12/22 AM":"NA", "12/22 PM":"NA","12/23 AM":"FULL", "12/23 PM":"DAY","12/24 AM":"NA", "12/24 PM":"A","12/25 AM":"A", "12/25 PM":"NA","12/26 AM":"A", "12/26 PM":"NA","12/27 AM":"FULL", "12/27 PM":"DAY"},' +
'{"Pro":"Leo Trimarchi", "12/21 AM":"A", "12/21 PM":"NA","12/22 AM":"NA", "12/22 PM":"A","12/23 AM":"FULL", "12/23 PM":"DAY","12/24 AM":"A", "12/24 PM":"NA","12/25 AM":"FULL", "12/25 PM":"DAY","12/26 AM":"FULL", "12/26 PM":"DAY","12/27 AM":"A", "12/27 PM":"A"}]';
$(function() {
ConvertToTable(jData);
});
function ConvertToTable(jData) {
var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
var $table = $('<table class="blueTable"/>');
var $headerTr = $('<tr/>');
for (var index in arrJSON[0]) {
$headerTr.append($('<th/>').html(index));
}
$table.append($headerTr);
for (var i = 0; i < arrJSON.length; i++) {
var $tableTr = $('<tr/>');
for (var index in arrJSON[i]) {
$tableTr.append($('<td/>').html(arrJSON[i][index]));
}
$table.append($tableTr);
}
$('body').append($table);
}