Convert JSON array to an HTML table in jQuery
Solution 1:
Using jQuery will make this simpler.
The following code will take an array of arrays and store convert them into rows and cells.
$.getJSON(url , function(data) {
var tbl_body = "";
var odd_even = false;
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
});
tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
odd_even = !odd_even;
});
$("#target_table_id tbody").html(tbl_body);
});
You could add a check for the keys you want to exclude by adding something like
var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
at the start of the getJSON callback function and adding:
if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}
around the tbl_row += line.
Edit: Was assigning a null variable previously
Edit: Version based on Timmmm's injection-free contribution.
$.getJSON(url , function(data) {
var tbl_body = document.createElement("tbody");
var odd_even = false;
$.each(data, function() {
var tbl_row = tbl_body.insertRow();
tbl_row.className = odd_even ? "odd" : "even";
$.each(this, function(k , v) {
var cell = tbl_row.insertCell();
cell.appendChild(document.createTextNode(v.toString()));
});
odd_even = !odd_even;
});
$("#target_table_id").append(tbl_body); //DOM table doesn't have .appendChild
});
Solution 2:
I'm not sure if is this that you want but there is jqGrid. It can receive JSON and make a grid.
Solution 3:
Make a HTML Table from a JSON array of Objects by extending $ as shown below
$.makeTable = function (mydata) {
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
tblHeader += "</tr>";
$(tblHeader).appendTo(table);
$.each(mydata, function (index, value) {
var TableRow = "<tr>";
$.each(value, function (key, val) {
TableRow += "<td>" + val + "</td>";
});
TableRow += "</tr>";
$(table).append(TableRow);
});
return ($(table));
};
and use as follows:
var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");
where TableCont is some div
Solution 4:
Pure HTML way, not vulnerable like the others AFAIK:
// Function to create a table as a child of el.
// data must be an array of arrays (outer array is rows).
function tableCreate(el, data)
{
var tbl = document.createElement("table");
tbl.style.width = "70%";
for (var i = 0; i < data.length; ++i)
{
var tr = tbl.insertRow();
for(var j = 0; j < data[i].length; ++j)
{
var td = tr.insertCell();
td.appendChild(document.createTextNode(data[i][j].toString()));
}
}
el.appendChild(tbl);
}
Example usage:
$.post("/whatever", { somedata: "test" }, null, "json")
.done(function(data) {
rows = [];
for (var i = 0; i < data.Results.length; ++i)
{
cells = [];
cells.push(data.Results[i].A);
cells.push(data.Results[i].B);
rows.push(cells);
}
tableCreate($("#results")[0], rows);
});