jQuery: Build table from JSON data
categories: javascript, jquery
Given data like:
var data = {
"GUEST" : {
"visits" : 1734070,
"visits_pct" : 74,
"users" : 1,
"net_pv" : 3432781,
"users_pct" : 0,
"pv_pct" : 13
},
"Logged In" : {
"visits" : 4240,
"visits_pct" : 0,
"users" : 177,
"net_pv" : 188112,
"users_pct" : 0,
"pv_pct" : 0
}
}
... a little jQuery ditty to make a table out of the data:
$.each(data,function(rowLabel,v) { if (! header) { $table.append(' <thead> <tr></tr> </thead> '); var $thead = $('thead tr',$table); $thead.append(' <th></th> '); $.each(v,function(headerLabel) { $thead.append(' <th>' + headerLabel + '</th> '); }); header = true; } $table.append(' <tr></tr> '); var $tr = $('tr:last',$table); $tr.append(' <th>' + rowLabel + '</th> '); $.each(v,function(j,cellData) { $tr.append(' <td>' + cellData + '</td> '); }) });
I'll come back and do something more interesting with this eventually, just wanted to jot it down for now.