我需要以自定义格式将json数据导出到html表中。
var data =[ { "ID":1, "Sl.No.":1, "325":25, "430":30, "2011":15, "1915":80 }, { "ID":1, "Sl.No.":2, "325":40, "430":30, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":3, "325":40, "430":25, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":4, "325":4, "430":2, "2011":1, "1915":20 }];
格式化所需的输出
ID Sl.No.
1 1 0325 25
1 1 0430 30
1 1 2011 15
1 1 1915 80
1 2 0325 40
1 2 0430 30
1 2 2011 20
1 2 1915 100
1 3 0325 40
1 3 0430 25
1 3 2011 20
1 3 1915 100
1 4 0325 4
1 4 0430 2
1 4 2011 1
1 4 1915 20
答案 0 :(得分:2)
答案 1 :(得分:1)
var data =[ { "ID":1, "Sl.No.":1, "325":25, "430":30, "2011":15, "1915":80 }, { "ID":1, "Sl.No.":2, "325":40, "430":30, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":3, "325":40, "430":25, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":4, "325":4, "430":2, "2011":1, "1915":20 }];
$a = $('#values')
$.each(data, function(index, value) {
$thisRow = $('<tr/>')
.append($('<td>' + value['ID'] + '</td>'))
.append($('<td>' + value['Sl.No.'] + '</td>'))
.append($('<td>' + '0325' + '</td>'))
.append($('<td>' + value['325'] + '</td>'))
for (var i = 0; i < 3; i++) {
if (i == 0)
key = '430';
if (i == 1)
key = '2011';
if (i == 2)
key = '1915';
$thisRow = $('<tr/>')
.append($('<td>' + value['ID'] + '</td>'))
.append($('<td>' + value['Sl.No.'] + '</td>'))
.append($('<td>' + key + '</td>'))
.append($('<td>' + value[key] + '</td>'));
$a.append($thisRow);
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="values"></table>
&#13;
答案 2 :(得分:0)
使用下面的代码
var data ='[{ "ID":1, "Sl.No.":1, "325":25, "430":30, "2011":15, "1915":80 }, { "ID":1, "Sl.No.":2, "325":40, "430":30, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":3, "325":40, "430":25, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":4, "325":4, "430":2, "2011":1, "1915":20 }]';
var str = JSON.parse(data);
var temp= '';
$.each(str,function(index, value){
var id = value.ID;
var slNo = value['Sl.No.'];
$.each(value, function(ind, val){
if(ind !='ID' && ind != 'Sl.No.' )
temp+='<tr><td>'+id+'</td><td>'+slNo+'</td><td>'+ind+
'</td><td>'+val+'</td></tr>';
});
});
$('#myTable tbody').append(temp);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="myTable" border="1">
<thead>
<th>Head 1</th>
<th>Head 2</th><th>Head 3</th><th>Head 4</th>
</thead>
<tbody></tbody>
</table>