我无法将 JSON 对象解析为 html 表。基本上我的 JSON 数据 [EDITED] 看起来像这样:
[
{
'category': 'Automotive (Motor)',
'month':8,
'month_now':'Aug',
'year':2018,
'lists':{
'total':1,
'price':591600
}
},
{
'category': 'Health',
'month_now':'Aug',
'month':8,
'year':2018,
'lists':{
'total':21,
'price':14448600
}
}
]
我想创建一个这样的表:
我想添加从 Jan 到 Des 的月份,如果每个月都没有总值,则使用空数据。
我已经阅读了很多关于JSON格式的知识,但我的知识非常有限,我需要帮助-__-
我正在尝试,这是我的代码:
$(document).ready(function () {
var json = [{'category': Automotive (Motor),'month': 8, 'month_now': 'Aug', 'year': 2018, 'lists': {'total': 1, 'price': 591600}}, {'category': Health, 'month_now': 'Aug', 'month': 8, 'year': 2018, 'lists': {'total': 21, 'price': 14448600}}];
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].category + "</td>");
tr.append("<td>" + json[i].month + "</td>");
tr.append("<td>" + json[i].lists + "</td>");
$('table').append(tr);
}
});
这是 html :
<table>
<tr>
<th>Category</th>
<th>Month</th>
<th>Total</th>
</tr>
</table>
最佳答案
- 您需要用引号将您的类别引起来。
- 从列表对象中获取
total
属性
$(document).ready(function() {
var json = [{
'category': 'Automotive (Motor)',
'month': 8,
'month_now': 'Aug',
'year': 2018,
'lists': {
'total': 1,
'price': 591600
}
}, {
'category': 'Health',
'month_now': 'Aug',
'month': 8,
'year': 2018,
'lists': {
'total': 21,
'price': 14448600
}
}];
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
for (var ii = 0; ii < 12; ii++) {
tr.append($('<td>'));
}
tr.find('td:eq(0)').html(json[i].category);
tr.find('td:eq('+json[i].month+')').html(json[i].lists.total);
$('table').append(tr);
}
});
table {
width: 100%;
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Unit</th>
<th>J</th>
<th>F</th>
<th>M</th>
<th>A</th>
<th>M</th>
<th>J</th>
<th>J</th>
<th>A</th>
<th>S</th>
<th>O</th>
<th>N</th>
<th>D</th>
</tr>
</table>
关于javascript - 使用 Javascript 按月将 JSON 解析为表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52143127/