我有一个JSON,我需要获取此JSON并将html作为ul li列表放入。它将值作为对象获取并在html中显示[object Object]。如果我修改json然后它工作。所以在我的脚本中可能存在一些错误,我无法正常循环访问json文件。有人可以帮忙吗:
我的JSON是:
[
{
"us":"USA"
},
{
"fr":"FRANCE"
},
{
"es":"Spain"
},
{
"sa":"South Africa"
}
]
AND JS IS
<script>
$.getJSON('jsonfile', function(data) {
var items = [];
$.each(data ,function(key,val) {
items.push('<li id="'+ key +'">' + val +'</li>');
});
$('<ul />' , {
'class':'new-div',
html:items.join('')
}).appendTo('body');
});
</script>
更新的JSON:
[
{
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
}
}
]
答案 0 :(得分:3)
你循环的data
是数组,它有对象。因此,您的key
将为0
,1
等,而val
将是数组中该位置的对象。< / p>
您的JSON结构实际上使输出有点麻烦,因为您的每个对象只有一个属性,但属性名称因对象而异。你可以通过循环对象属性来完成它,即使它们只有一个:
var items = [];
$.each(data ,function(outerKey, outerVal) { // <== Loops through the array
$.each(outerVal, function(key, val) { // <== "Loops" through each object's properties
items.push('<li id="'+ key +'">' + val +'</li>');
});
});
...但我改变了JSON结构。例如,假设密钥是唯一的,您的原始代码将适用于此结构:
{
"us":"USA",
"fr":"FRANCE",
"es":"Spain",
"sa":"South Africa"
}