Created
March 10, 2014 08:04
-
-
Save son0fhobs/9461138 to your computer and use it in GitHub Desktop.
Json to HTML Table
This file contains 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
// even/odd, classes, filters | |
var args = { | |
tableId:'', | |
firstRowHeaders:false, | |
} | |
function generate_html_table(data, args){ | |
if(data === 'undefined' || !data || !data[0]){ | |
return 'No Vals set. Ensure it's array or array of objects, or json string'; | |
} | |
var trClass = ''; | |
var tdClass = ''; | |
var html = ''; | |
var headers = []; | |
var dataType = 'json'; | |
if(typeof data === 'string'){ | |
json_obj = JSON.stringify(data); | |
}else{ | |
if( data.constructor == [].constructor){ | |
dataType = 'array'; | |
maxCells = data[0].length; | |
} | |
} | |
if(dataType === 'json'){ | |
html += '<thead><tr>'; | |
for(key in data[0]){ | |
header = uppercaseWords(key.replace(/[^a-zA-Z]+/gi, ' ')); | |
html += '<th class="'+key+'">'+header+'</th>'; | |
} | |
html += '</thead></tr>'; | |
} | |
max = data.length; | |
// cycle through rows | |
for(i=0;i<max;i++){ | |
trClass = (i%2) ? 'row-even' : 'row-odd'; | |
html += '<tr class="'+trClass+'">'; | |
// cycle through cells, depending on if obj or array | |
if(dataType === 'json'){ | |
for(key in data[i]){ | |
tdClass = key; | |
html += '<td class="'+tdClass+'">'+data[i][key]+'</td>'; | |
} | |
}else{ | |
for(c=0;c<maxCells;c++){ | |
tdClass = (c%2) ? 'col-even' : 'col-odd'; | |
html += '<td class="'+tdClass+'">'+data[i][c]+'</td>'; | |
} | |
} | |
html += '</tr>'; | |
} | |
html += '</tbody>'; | |
html = '<table>'+html+'</table>'; | |
return html; | |
} | |
function uppercaseWords(string){ | |
return string.charAt(0).toUpperCase() + string.slice(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment