我是jQuery和JSON的新手。我需要解析以下格式的JSON,以便填充html表tbody:
{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}
但我不知道如何访问它们,所以以下列方式获取html表:
header1 header2 header3
name0 id0 amt0
name1 id1 amt1
答案 0 :(得分:9)
未经测试,但可能类似于:
var jsondata=$.parseJSON('{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}');
$.each(jsondata.response, function(i, d) {
var row='<tr>';
$.each(d, function(j, e) {
row+='<td>'+e+'</td>';
});
row+='</tr>';
$('#table tbody').append(row);
});
答案 1 :(得分:0)
您可以使用此Javascript表达式访问JSON结构:
var matrix = {"response":[["name0","id0","amt0"],["name1","id1","amt1"]]};
第i个元素的第j列可通过以下方式访问:
matrix.response[i][j]
答案 2 :(得分:0)
在关注HTML之后调用jsonToHtmlTable(jsonObj, '#records');
(例如,在文档就绪中)
HTML
<table id="records">
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
的JavaScript
//Sample JSON Object (array of json objects)
var jsonObj = [{"a":1,"b":3,"ds":4},{"a":2,"b":5,"ds":4}];
//Use
$(document).ready(function(){
jsonToHtmlTable(jsonObj, '#records');
});
//implementation
function jsonToHtmlTable(jsonObj, selector) {
addColumns(jsonObj, selector);
addRows(jsonObj, selector);
}
function addColumns(jsonObj, selector) {
if (!$.isArray(jsonObj) || jsonObj.length < 1)
return;
var object = jsonObj[0];
var theadHtml = "";
for (var property in object) {
if (object.hasOwnProperty(property))
theadHtml += "<th>" + property + "</th>";
}
$(selector + ' thead tr').html(theadHtml);
}
function addRows() {
var tbody = $(selector + ' tbody');
$.each(jsonObj, function (i, d) {
var row = '<tr>';
$.each(d, function (j, e) {
row += '<td>' + e + '</td>';
});
row += '</tr>';
tbody.append(row);
});
}