将json数据转换为html表

将json数据转换为html表

是否有任何jQuery或javascript库生成给定JSON数据的动态表?我不想定义列,库应该读取json散列中的键并生成列。

当然,我自己也可以遍历json数据并生成html表。我只想知道是否存在这样的库,我可以简单地重用。


繁星淼淼
浏览 1201回答 3
3回答

繁华开满天机

我用vanillajs重写了您的代码,使用DOM方法来防止html注入。演示var _table_ = document.createElement('table'),&nbsp; _tr_ = document.createElement('tr'),&nbsp; _th_ = document.createElement('th'),&nbsp; _td_ = document.createElement('td');// Builds the HTML Table out of myList json data from Ivy restful service.function buildHtmlTable(arr) {&nbsp; var table = _table_.cloneNode(false),&nbsp; &nbsp; columns = addAllColumnHeaders(arr, table);&nbsp; for (var i = 0, maxi = arr.length; i < maxi; ++i) {&nbsp; &nbsp; var tr = _tr_.cloneNode(false);&nbsp; &nbsp; for (var j = 0, maxj = columns.length; j < maxj; ++j) {&nbsp; &nbsp; &nbsp; var td = _td_.cloneNode(false);&nbsp; &nbsp; &nbsp; cellValue = arr[i][columns[j]];&nbsp; &nbsp; &nbsp; td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));&nbsp; &nbsp; &nbsp; tr.appendChild(td);&nbsp; &nbsp; }&nbsp; &nbsp; table.appendChild(tr);&nbsp; }&nbsp; return table;}// 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 recordsfunction addAllColumnHeaders(arr, table) {&nbsp; var columnSet = [],&nbsp; &nbsp; tr = _tr_.cloneNode(false);&nbsp; for (var i = 0, l = arr.length; i < l; i++) {&nbsp; &nbsp; for (var key in arr[i]) {&nbsp; &nbsp; &nbsp; if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {&nbsp; &nbsp; &nbsp; &nbsp; columnSet.push(key);&nbsp; &nbsp; &nbsp; &nbsp; var th = _th_.cloneNode(false);&nbsp; &nbsp; &nbsp; &nbsp; th.appendChild(document.createTextNode(key));&nbsp; &nbsp; &nbsp; &nbsp; tr.appendChild(th);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; table.appendChild(tr);&nbsp; return columnSet;}document.body.appendChild(buildHtmlTable([{&nbsp; &nbsp; "name": "abc",&nbsp; &nbsp; "age": 50&nbsp; },&nbsp; {&nbsp; &nbsp; "age": "25",&nbsp; &nbsp; "hobby": "swimming"&nbsp; },&nbsp; {&nbsp; &nbsp; "name": "xyz",&nbsp; &nbsp; "hobby": "programming"&nbsp; }]));
打开App,查看更多内容
随时随地看视频慕课网APP