我是否有一种非常简单的方法可以获取一组JSON对象并将其转换为HTML表,不包括几个字段?或者我是否必须手动执行此操作?
答案 0 :(得分:76)
使用jQuery会使这更简单。
以下将采用数组数组并将它们转换为行和单元格。
$.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);
});
您可以通过添加类似
的内容添加对要排除的键的检查var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}
围绕tbl_row + =行。
编辑:之前正在分配一个空变量
修改:版本基于Timmmm的injection-free贡献。
$.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").appendChild(tbl_body);
});
答案 1 :(得分:33)
我不确定这是否是您想要的,但有jqGrid。它可以接收JSON并制作网格。
答案 2 :(得分:13)
通过扩展$,从JSON对象数组中创建一个HTML表,如下所示
$.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));
};
并使用如下:
var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");
其中TableCont是div
答案 3 :(得分:9)
纯HTML方式,不像其他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);
}
使用示例:
$.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);
});
答案 4 :(得分:6)
要将2D JavaScript数组转换为HTML表,您只需要一些代码:
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$('body').append(arrayToTable([
["John","Slegers",34],
["Tom","Stevens",25],
["An","Davies",28],
["Miet","Hansen",42],
["Eli","Morris",18]
]));
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
如果要从JSON文件加载2D数组,还需要一些Ajax代码:
$.ajax({
type: "GET",
url: "data.json",
dataType: 'json',
success: function (data) {
$('body').append(arrayToTable(data));
}
});
答案 5 :(得分:5)
对于非常高级的JSON对象到HTML表格,您可以尝试基于此My jQuery Solution的closed thread。
var myList=[{"name": "abc","age": 50},{"name": {"1": "piet","2": "jan","3": "klaas"},"age": "25","hobby": "watching tv"},{"name": "xyz","hobby": "programming","subtable": [{"a": "a","b": "b"},{"a": "a","b": "b"}]}];
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable() {
addTable(myList, $("#excelDataTable"));
}
function addTable(list, appendObj) {
var columns = addAllColumnHeaders(list, appendObj);
for (var i = 0; i < list.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = list[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
if (cellValue.constructor === Array)
{
$a = $('<td/>');
row$.append($a);
addTable(cellValue, $a);
} else if (cellValue.constructor === Object)
{
var array = $.map(cellValue, function (value, index) {
return [value];
});
$a = $('<td/>');
row$.append($a);
addObject(array, $a);
} else {
row$.append($('<td/>').html(cellValue));
}
}
appendObj.append(row$);
}
}
function addObject(list, appendObj) {
for (var i = 0; i < list.length; i++) {
var row$ = $('<tr/>');
var cellValue = list[i];
if (cellValue == null) {
cellValue = "";
}
if (cellValue.constructor === Array)
{
$a = $('<td/>');
row$.append($a);
addTable(cellValue, $a);
} else if (cellValue.constructor === Object)
{
var array = $.map(cellValue, function (value, index) {
return [value];
});
$a = $('<td/>');
row$.append($a);
addObject(array, $a);
} else {
row$.append($('<td/>').html(cellValue));
}
appendObj.append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(list, appendObj)
{
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < list.length; i++) {
var rowHash = list[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
appendObj.append(headerTr$);
return columnSet;
}
答案 6 :(得分:2)
您可以使用接受JSON数据的jQuery插件来填充表格。 jsonTable
答案 7 :(得分:1)
我在这里发现了一个副本:Convert json data to a html table
嗯,有很多插件存在,包括商业插件(将其设为商业项目?!有点过头......但你可以在这里结账:https://github.com/alfajango/jquery-dynatable)
这个有更多的分叉:https://github.com/afshinm/Json-to-HTML-Table
//Example data, Object
var objectArray = [{
"Total": "34",
"Version": "1.0.4",
"Office": "New York"
}, {
"Total": "67",
"Version": "1.1.0",
"Office": "Paris"
}];
//Example data, Array
var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"];
//Example data, nested Object. This data will create nested table also.
var nestedTable = [{
key1: "val1",
key2: "val2",
key3: {
tableId: "tblIdNested1",
tableClassName: "clsNested",
linkText: "Download",
data: [{
subkey1: "subval1",
subkey2: "subval2",
subkey3: "subval3"
}]
}
}];
应用代码
//Only first parameter is required
var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');
或者你也可以查看这个jQuery插件:https://github.com/jongha/jquery-jsontotable
我认为jongha的插件更易于使用
<div id="jsontotable" class="jsontotable"></div>
var data = [[1, 2, 3], [1, 2, 3]];
$.jsontotable(data, { id: '#jsontotable', header: false });
答案 8 :(得分:1)
使用纯jquery:
window.jQuery.ajax({
type: "POST",
url: ajaxUrl,
contentType: 'application/json',
success: function (data) {
var odd_even = false;
var response = JSON.parse(data);
var head = "<thead class='thead-inverse'><tr>";
$.each(response[0], function (k, v) {
head = head + "<th scope='row'>" + k.toString() + "</th>";
})
head = head + "</thead></tr>";
$(table).append(head);//append header
var body="<tbody><tr>";
$.each(response, function () {
body=body+"<tr>";
$.each(this, function (k, v) {
body=body +"<td>"+v.toString()+"</td>";
})
body=body+"</tr>";
})
body=body +"</tbody>";
$(table).append(body);//append body
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responsetext);
}
});
答案 9 :(得分:1)
如果您接受使用其他 jQuery 依赖工具,我建议您使用Tabulator。然后,您将不需要编写HTML或任何其他DOM生成代码,同时在表格数据的格式化和处理方面保持极大的灵活性。
对于使用 Node 的另一个工作示例,您可以查看MMM-Tabulator演示项目。
答案 10 :(得分:1)
您可以使用Javascript + Jquery轻松完成此操作,如下所示。 如果要排除某些列,只需在for循环内编写if语句以跳过这些列。希望这会有所帮助!
//Sample JSON 2D array
var json = [{
"Total": "34",
"Version": "1.0.4",
"Office": "New York"
}, {
"Total": "67",
"Version": "1.1.0",
"Office": "Paris"
}];
// Get Table headers and print
for (var k = 0; k < Object.keys(json[0]).length; k++) {
$('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');
}
// Get table body and print
for (var i = 0; i < Object.keys(json).length; i++) {
$('#table_content').append('<tr>');
for (var j = 0; j < Object.keys(json[0]).length; j++) {
$('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');
}
$('#table_content').append('</tr>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr id="table_head">
</tr>
</thead>
<tbody id="table_content">
</tbody>
</table>
答案 11 :(得分:0)
修改了@ Dr.sai代码的位代码。希望这会有用。
(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);
希望这也有助于隐藏一些列。 Link to file
答案 12 :(得分:0)
根据上面@ Dr.sai的回答,在左侧显示带有标题的单行视图。
jQuery的.text方法
阻止了注入$.makeTable = function (mydata) {
var table = $('<table>');
$.each(mydata, function (index, value) {
// console.log('index '+index+' value '+value);
$(table).append($('<tr>'));
$(table).append($('<th>').text(index));
$(table).append($('<td>').text(value));
});
return ($(table));
};
答案 13 :(得分:0)
一种简单的方法是:
var data = [{
"Total": 34,
"Version": "1.0.4",
"Office": "New York"
}, {
"Total": 67,
"Version": "1.1.0",
"Office": "Paris"
}];
drawTable(data);
function drawTable(data) {
// Get Table headers and print
var head = $("<tr />")
$("#DataTable").append(head);
for (var j = 0; j < Object.keys(data[0]).length; j++) {
head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));
}
// Print the content of rows in DataTable
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#DataTable").append(row);
row.append($("<td>" + rowData["Total"] + "</td>"));
row.append($("<td>" + rowData["Version"] + "</td>"));
row.append($("<td>" + rowData["Office"] + "</td>"));
}
table {
border: 1px solid #666;
width: 100%;
text-align: center;
}
th {
background: #f8f8f8;
font-weight: bold;
padding: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="DataTable"></table>
答案 14 :(得分:-1)
更短的方式
$.makeTable = function (mydata) {
if (mydata.length <= 0) return "";
return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) {
return "<th>" + key + "</th>";
}).join("\n") + "</tr>").append($.map(mydata, function (index, value) {
return "<tr>" + $.map(index, function (val, key) {
return "<td>" + val + "</td>";
}).join("\n") + "</tr>";
}).join("\n"));
};