Skip to content

Instantly share code, notes, and snippets.

@James1x0
Created August 20, 2014 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save James1x0/5064e59ffec30ef4eac5 to your computer and use it in GitHub Desktop.
Save James1x0/5064e59ffec30ef4eac5 to your computer and use it in GitHub Desktop.
JSON To HTML table
/*
Quick and dirty JSON to HTML table parser
---
Designed for use debugging in node.js
*/
function jsonToHtml ( json, limit ) {
var data = json,
dataKeys = [];
if( !data ) {
winston.log('error', chalk.bgRed('No data! Cannot render HTML.'));
return;
}
if( limit ) {
console.log(limit);
data = data.slice(0, limit);
}
var html = '<html>' +
'<head><style>table { border: 1px solid #666; width: 100%; } th {background: #f8f8f8; font-weight: bold; padding: 2px; } tr:nth-child(even) { background-color: #F5F5F5; } .blankfield { background-color: rgba(255, 0, 0, 0.1); }</style></head>' +
'<body>',
tb = '',
tbh = '';
data.forEach(function ( item ) {
var itemRow = [],
itemCol = {};
for ( var key in item ) {
if( dataKeys.indexOf( key ) < 0 ) {
tbh += '<th>' + key + '</th>';
dataKeys.push(key);
}
itemCol[ key ] = '<td class="' + key + '">' + item[ key ] + '</td>';
}
dataKeys.forEach(function ( dataKey, index ) {
var colHtml = itemCol[ dataKey ],
colTd = ( colHtml ) ? colHtml : '<td class="blankfield"></td>';
itemRow[ index ] = colTd;
});
tb += '<tr>' + itemRow.join('') + '</tr>';
});
html += '<table><tr>' + tbh + '</tr>' + tb + '</table></body></html>';
return html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment