我正在尝试将以下JSON数据转换为HTML表格。这是我到目前为止所尝试的。当我运行下面的脚本时,表行中的值没有得到适当的填充。我尝试更改JSON数据的格式,但也没有带来预期的结果。
这是我的Sample JSON数据(在raw_answers.json文件中):
{
"links": {
"self": "https://url"
},
"data": [
{
"type": "assignments",
"id": "378778ef-62f9",
"attributes": {
"title": "What is the day today",
"created_at": "2017-07-09T15:14:09Z"
},
"links": {
"teaching": "https://url"
}
}
]
}
这是我的代码:
<script>
$(document).ready(function () {
$.getJSON("raw_answers.json", function (data) {
var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
$.each(data, function (index, value) {
arrItems.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
});
// EXTRACT VALUE FOR TABLE HEADER.
var col = [];
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
</script>
任何帮助都将受到高度赞赏。