如何将 JSON 对象转换为 HTML 表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20467785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a JSON Object into a HTML table?
提问by user2565192
I've got a JSON object that looks like this:
我有一个看起来像这样的 JSON 对象:
{"a": 1, "b": 3, "ds": 4}
I'd like to convert it into a HTML table that looks like this:
我想将其转换为如下所示的 HTML 表格:
name | Value
a 1
b 3
ds 4
Could anyone tell me how to achieve this?
谁能告诉我如何实现这一目标?
回答by Chalist
It's very simple with jQuery:
使用 jQuery 非常简单:
$(function() {
var jsonObj = $.parseJSON('{"a":1,"b":3,"ds":4}');
var html = '<table border="1">';
$.each(jsonObj, function(key, value) {
html += '<tr>';
html += '<td>' + key + '</td>';
html += '<td>' + value + '</td>';
html += '</tr>';
});
html += '</table>';
$('div').html(html);
});
Here is link to the working fiddle.
这是工作小提琴的链接。
UPDATE:an alternative way to achieve this is by using a library called dynatableto convert the JSON into a sortable table.
更新:实现此目的的另一种方法是使用名为 dynatable 的库将 JSON 转换为可排序的表。
回答by Aurélien Gasser
You can use javascript:
您可以使用 javascript:
<script type="text-javascript">
var data = {
"a": 1,
"b": 3,
"ds": 4
};
// Create a new table
var table = document.createElement("table");
// Add the table header
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = "Name";
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = "Value";
tr.appendChild(rightRow);
table.appendChild(tr);
// Add the table rows
for (var name in data) {
var value = data[name];
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = name;
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = value;
tr.appendChild(rightRow);
table.appendChild(tr);
}
// Add the created table to the HTML page
document.body.appendChild(table);
</script>
The resulting HTML structure is:
生成的 HTML 结构是:
<table>
<tr>
<td>Name</td>
<td>Value</td>
</tr>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>3</td>
</tr>
<tr>
<td>ds</td>
<td>4</td>
</tr>
</table>
Here is the link to the working fiddle.
这是工作小提琴的链接。
回答by Alex
You should take a look at Knockout.js, with that, you can take your JSON data and bind it to HTML elements.
您应该查看Knockout.js,通过它,您可以获取 JSON 数据并将其绑定到 HTML 元素。
Updating is then done automatically, so you don't have to mess with that by yourself.
然后更新会自动完成,因此您不必自己搞砸。
Here is a list of examples.
这是示例列表。