我尝试循环这个 json 但它不起作用。我想循环遍历商店但它不起作用
JSON:
{
"type": "shops",
"shops": {
"1": {
"id": "1",
"name": "abcd",
"open_time": "9AM",
"closed_time": "9PM"
},
"2": {
"id": "1",
"name": "efgh",
"open_time": "9AM",
"closed_time": "9PM"
}
}
}
脚本
$.getJSON( "simple.json", function( json ) {
console.log( "JSON Data: " + (json) );
for(var i = 0; i < json.shops.length; i++){
console.log(json[i].shops.name);
}
});
这没有给我任何结果
最佳答案
json.shops
不是一个数组,它是一个对象。您可以使用 for..in
循环或 $.each
使用 $.each
$.getJSON( "simple.json", function( json ) {
console.log( "JSON Data: " + (json) );
$.each(json.shops, function(key, shop){
//key will be "1", "2"...n
console.log(shop.name, shop.id);
});
});
使用 for..in
for(var shop in json.shops){
//shop will be "1", "2"...n
if (json.shops.hasOwnProperty(shop))
console.log(json.shops[shop].name);
}
关于javascript - 如何使用 javascript 遍历这个 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32825485/