Parsing JSON objects for HTML table
我正在尝试显示一个基于JSON数据的"排行榜"表。
我读了很多关于JSON格式的文章,克服了一些最初的障碍,但是我的javascript知识非常有限,我需要帮助!
基本上,我的JSON数据看起来是这样的:
1 | [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}] |
我需要的是能够遍历这个数组,为每个对象生成一个表行或列表项。数组中的对象总数未知,但每个对象的格式都相同—有三个值:名称、得分、团队。
到目前为止,我已经使用了以下代码,它确认我已经成功地在控制台中加载了对象。-
1 2 3 4 | $.getJSON(url, function(data){ console.log(data); }); |
但是我不知道如何迭代它们,将它们解析成HTML表。
下一步是按分数降序排列条目…
任何帮助都将不胜感激。谢谢!
编辑:
更新了下面的代码,这项工作:
1 2 3 4 5 6 7 8 9 10 11 | $.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); } }); |
(不需要$.Parsejson,我们可以使用'Data',因为我相信JSON数组已经被解析了)
在每个对象上循环,每次迭代都附加一个带有相关数据的表行。
1 2 3 4 5 6 7 8 9 10 11 12 13 | $(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); } }); }); |
杰西德
您可以使用简单的jquery jput插件
http://plugins.jquery.com/jput/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $(document).ready(function(){ var json = [{"name":"name1","score":"30 <p><center>[wp_ad_camp_1]</center></p><hr><P>循环遍历每个对象,推入字符串数组并将它们联接起来。在目标表中追加,更好。</P>[cc lang="javascript"]$(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(''))); }); |
您可以将knockoutjs与jquery一起使用。knockoutjs具有智能数据绑定功能。通过使用foreach绑定功能,您可以编写如下示例所示的代码:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <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:
1 2 3 4 5 6 7 8 9 | $(document).ready(function () { $.getJSON(url,function (json) { ko.applyBindings({ teams: json }); } }); }); |
用你的虚拟数据摆弄演示
Make a HTML Table from a JSON array of Objects by extending $ as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $.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)); }; |
使用方法如下:
1 2 3 | var mydata = eval(jdata); var table = $.makeTable(mydata); $(table).appendTo("#TableCont"); |
TableCont在哪?
从嵌套的JSON对象(当前不支持数组)生成HTML的另一种好的递归方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | // 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> '; }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> '; s += tab(++tabs)+'<table class="'+css_class+'"> '; for (var k in json){ s += tab(++tabs)+'<tr> '; s += tab(++tabs)+'<td>' + k + '</td> '; s += generate_td(json[k]); s += tab(--tabs)+'</tr>' + tab(--tabs) + ' '; } // close the <td>...</td> external block s += tab(tabs--)+'</table> '; s += tab(tabs--)+'</td> '; return s; } } // construct the complete HTML code var html_code = '' ; html_code += tab(++tabs)+'<table class="'+css_class+'"> '; html_code += tab(++tabs)+'<tr> '; html_code += generate_td(json); html_code += tab(tabs--)+'</tr> '; html_code += tab(tabs--)+'</table> '; return html_code; } |
这个代码会有很大帮助
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | function isObject(data){ var tb = document.createElement("table"); if(data !=null) { var keyOfobj = Object.keys(data); var ValOfObj = Object.values(data); for (var i = 0; i < keyOfobj.length; i++) { var tr = document.createElement('tr'); var td = document.createElement('td'); var key = document.createTextNode(keyOfobj[i]); td.appendChild(key); tr.appendChild(td); tb.appendChild(tr); if(typeof(ValOfObj[i]) =="object") { if(ValOfObj[i] !=null) { tr.setAttribute("style","font-weight: bold"); isObject(ValOfObj[i]); } else { var td = document.createElement('td'); var value = document.createTextNode(ValOfObj[i]); td.appendChild(value); tr.appendChild(td); tb.appendChild(tr); } } else { var td = document.createElement('td'); var value = document.createTextNode(ValOfObj[i]); td.appendChild(value); tr.appendChild(td); tb.appendChild(tr); } } } } |
这是一个丑陋的,但只是想扔在那里的一些其他选择的组合。这个没有回路。我用它来调试
1 2 3 4 5 | 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) |
例子:
1 2 3 4 5 | 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) |
1 | #myDiv table td{background:whitesmoke;border:1px solid lightgray} |
1 2 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> table goes here |
Here is an another way to parse json object into Html table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | //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); |
1 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> |
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:
https://github.com/ColdSIce/ReportUI
Now it is an angular 4 module. You can pass your json data to TableLayoutComponent and get a HTML table as 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.
If you are interested you can join me in this project and help.
使用或不使用jquery,有两种方法可以完成相同的工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // jquery way $(document).ready(function () { var json = [{"User_Name":"John Doe","score":"10","team":"1 <p><center>[wp_ad_camp_3]</center></p><hr><P>这篇文章对你们大家都很有帮助</P><P>首先使用jquery eval parser解析json数据,然后通过jquery进行iterarate,下面的每个函数都是代码截图:</P>[cc lang="javascript"] var obj = eval("(" + data.d +")"); alert(obj); $.each(obj, function (index,Object) { var Id = Object.Id; var AptYear = Object.AptYear; $("#ddlyear").append('<option value=' + Id + '>' + AptYear + '</option>').toString(); }); |