jQuery 解析 HTML 表的 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17066636/
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
Parsing JSON objects for HTML table
提问by user2478342
I am trying to display a "leaderboard" table based on JSON data.
我正在尝试基于 JSON 数据显示“排行榜”表。
I have read a lot about the JSON format and overcome some initial obstacles, but my Javascript knowledge is very limited and I need help!
我已经阅读了很多关于 JSON 格式的内容并克服了一些最初的障碍,但我的 Javascript 知识非常有限,我需要帮助!
Basically my JSON data comes through looking like this:
基本上我的 JSON 数据看起来像这样:
[{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}]
What I need is to be able to loop through this array, generating a table row or list item for each object. There will be an unknown amount of total objects in the array but each will have the same format- three values: Name, Score, Team.
我需要的是能够遍历这个数组,为每个对象生成一个表行或列表项。数组中的总对象数量未知,但每个对象都具有相同的格式 - 三个值:名称、分数、团队。
So far I have used the following code, which confirms that I am successfully loading the objects in the console-
到目前为止,我已经使用了以下代码,它确认我已成功加载控制台中的对象-
$.getJSON(url,
function(data){
console.log(data);
});
but I am not sure how to iterate over them, parsing them into the HTML table.
但我不确定如何迭代它们,将它们解析到 HTML 表中。
The next step is sorting the entries by score in descending order...
下一步是按分数按降序对条目进行排序...
Any help would be much appreciated. Thanks!
任何帮助将非常感激。谢谢!
EDIT:
编辑:
Updated code below, this works:
下面更新了代码,这有效:
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
}
});
(The $.parseJSON was not necessary, we can use 'data' as the JSON array is already parsed I believe)
($.parseJSON 不是必需的,我们可以使用“数据”,因为我相信 JSON 数组已经解析)
回答by pmandell
Loop over each object, appending a table row with the relevant data each iteration.
循环遍历每个对象,在每次迭代时附加带有相关数据的表行。
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
}
});
});
回答by shabeer
You can use simple jQuery jPut plugin
您可以使用简单的 jQuery jPut 插件
http://plugins.jquery.com/jput/
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","score":"30"},{"name": "name2","score":"50"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<div jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{score}}</td>
</tr>
</div>
<table>
<tbody id="tbody">
</tbody>
</table>
回答by Kamruzzaman
Loop over each object, push in string array and join them. Append in target table, it is better.
循环遍历每个对象,推入字符串数组并加入它们。附加在目标表中,效果更好。
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr=[];
for (var i = 0; i < json.length; i++) {
tr.push('<tr>');
tr.push("<td>" + json[i].User_Name + "</td>");
tr.push("<td>" + json[i].score + "</td>");
tr.push("<td>" + json[i].team + "</td>");
tr.push('</tr>');
}
$('table').append($(tr.join('')));
});
回答by Aminul
You can use KnockoutJSwith jQuery. KnockoutJS have smart data-binding features. By using the foreach bindingfeature you can write your code like this example:
您可以将KnockoutJS与 jQuery 一起使用。KnockoutJS 具有智能数据绑定功能。通过使用 foreach 绑定功能,您可以像下面这样编写代码:
HTML:
HTML:
<table>
<thead>
<tr>
<th>User Name</th>
<th>Score</th>
<th>Team</th>
</tr>
</thead>
<tbody data-bind="foreach: teams">
<tr>
<td data-bind="text: User_Name"></td>
<td data-bind="text: score "></td>
<td data-bind="text: team "></td>
</tr>
</tbody>
</table>
JavaScript:
JavaScript:
$(document).ready(function () {
$.getJSON(url,function (json) {
ko.applyBindings({
teams: json
});
}
});
});
Fiddle Demowith your dummy data
使用您的虚拟数据进行Fiddle Demo
回答by Dr.sai
Make a HTML Table from a JSON array of Objects by extending $ as shown below
通过扩展 $ 从对象的 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));
};
and use as follows:
并使用如下:
var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");
where TableCont is some div
其中 TableCont 是一些 div
回答by chenchuk
another nice recursive way to generate HTML from a nested JSON object (currently not supporting arrays):
从嵌套的 JSON 对象(目前不支持数组)生成 HTML 的另一种不错的递归方式:
// generate HTML code for an object
var make_table = function(json, css_class='tbl_calss', tabs=1){
// helper to tabulate the HTML tags. will return '\t\t\t' for num_of_tabs=3
var tab = function(num_of_tabs){
var s = '';
for (var i=0; i<num_of_tabs; i++){
s += '\t';
}
//console.log('tabbing done. tabs=' + tabs)
return s;
}
// recursive function that returns a fixed block of <td>......</td>.
var generate_td = function(json){
if (!(typeof(json) == 'object')){
// for primitive data - direct wrap in <td>...</td>
return tab(tabs) + '<td>'+json+'</td>\n';
}else{
// recursive call for objects to open a new sub-table inside the <td>...</td>
// (object[key] may be also an object)
var s = tab(++tabs)+'<td>\n';
s += tab(++tabs)+'<table class="'+css_class+'">\n';
for (var k in json){
s += tab(++tabs)+'<tr>\n';
s += tab(++tabs)+'<td>' + k + '</td>\n';
s += generate_td(json[k]);
s += tab(--tabs)+'</tr>' + tab(--tabs) + '\n';
}
// close the <td>...</td> external block
s += tab(tabs--)+'</table>\n';
s += tab(tabs--)+'</td>\n';
return s;
}
}
// construct the complete HTML code
var html_code = '' ;
html_code += tab(++tabs)+'<table class="'+css_class+'">\n';
html_code += tab(++tabs)+'<tr>\n';
html_code += generate_td(json);
html_code += tab(tabs--)+'</tr>\n';
html_code += tab(tabs--)+'</table>\n';
return html_code;
}
回答by kevguy
Here are two ways to do the same thing, with or without jQuery:
这里有两种方法可以做同样的事情,有或没有 jQuery:
// jquery way
$(document).ready(function () {
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').first().append(tr);
}
});
// without jquery
function ready(){
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];
const table = document.getElementsByTagName('table')[1];
json.forEach((obj) => {
const row = table.insertRow(-1)
row.innerHTML = `
<td>${obj.User_Name}</td>
<td>${obj.score}</td>
<td>${obj.team}</td>
`;
});
};
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
ready();
} else {
document.addEventListener('DOMContentLoaded', ready);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>User_Name</th>
<th>score</th>
<th>team</th>
</tr>
</table>'
<table>
<tr>
<th>User_Name</th>
<th>score</th>
<th>team</th>
</tr>
</table>
回答by Secret Aga
I spent a lot of time developing various reports. So, now I have an idea - create a web framework for building web reports. I have started here:
我花了很多时间开发各种报告。所以,现在我有了一个想法——创建一个用于构建 Web 报告的 Web 框架。我从这里开始:
https://github.com/ColdSIce/ReportUI
https://github.com/ColdSIce/ReportUI
Now it is an angular 4module. You can pass your jsondata to TableLayoutComponent and get a HTML tableas result. Table already has fixed header. Also you can fix some your columns by default or by click. More there, you can customize table properties like background-color, font-color, row-height etc.
现在它是一个angular 4模块。您可以将您的 json数据传递给 TableLayoutComponent 并获得一个 HTML 表格作为结果。表已经有固定的标题。您也可以默认或通过单击修复某些列。在那里,您可以自定义表格属性,如背景颜色、字体颜色、行高等。
If you are interested you can join me in this project and help.
如果你有兴趣,你可以和我一起参与这个项目并提供帮助。
回答by Bavyasrisekar
Here is an another way to parse json object into Html table
这是将json对象解析为Html表的另一种方法
//EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < d.length; i++) {
for (var key in d[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 < d.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = d[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 src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
回答by jleviaguirre
This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes
这个很丑,但只是想把其他一些选择放在一起。这个没有循环。我将它用于调试目的
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
Example:
例子:
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='myDiv'>table goes here</div>