Created
August 20, 2014 20:01
-
-
Save James1x0/5064e59ffec30ef4eac5 to your computer and use it in GitHub Desktop.
JSON To HTML table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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