Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?
I'm not sure if is this that you want but there is jqGrid. It can receive JSON and make a grid.
Modified a bit code of @Dr.sai 's code. Hope this will be useful.
(function ($) {
/**
* data - array of record
* hidecolumns, array of fields to hide
* usage : $("selector").generateTable(json, ['field1', 'field5']);
*/
'use strict';
$.fn.generateTable = function (data, hidecolumns) {
if ($.isArray(data) === false) {
console.log('Invalid Data');
return;
}
var container = $(this),
table = $('<table>'),
tableHead = $('<thead>'),
tableBody = $('<tbody>'),
tblHeaderRow = $('<tr>');
$.each(data, function (index, value) {
var tableRow = $('<tr>').addClass(index%2 === 0 ? 'even' : 'odd');
$.each(value, function (key, val) {
if (index == 0 && $.inArray(key, hidecolumns) <= -1 ) {
var theaddata = $('<th>').text(key);
tblHeaderRow.append(theaddata);
}
if ($.inArray(key, hidecolumns) <= -1 ) {
var tbodydata = $('<td>').text(val);
tableRow.append(tbodydata);
}
});
$(tableBody).append(tableRow);
});
$(tblHeaderRow).appendTo(tableHead);
tableHead.appendTo(table);
tableBody.appendTo(table);
$(this).append(table);
return this;
};
})(jQuery);
Hoping this will be helpful to hide some columns too. Link to file
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);
});