我尝试循环这个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);
}
});
这不会给我任何结果
答案 0 :(得分:4)
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);
}
答案 1 :(得分:1)
如评论所示,商店是一个对象,而不是一个数组。您可以使用以下方法遍历javascript对象的所有属性:
$.getJSON( "simple.json", function( json ) {
console.log( "JSON Data: " + (json) );
for(var key in json.shops){
if (!json.shops.hasOwnProperty(key)) continue;
console.log(json.shops[key]);
}
});
答案 2 :(得分:0)
json.shops.length
未定义,因为shops
是一个对象而不是一个数组,并且(在这种情况下)没有“length”属性。但是每个JavaScript对象都可以拥有属性,并且这些属性名称可以作为列表检索,然后您可以迭代:
for(var i = 0; i < Object.keys(json.shops).length; i++){
console.log(json.shops[Object.keys(json.shops)][i].name);
}
或者,或者,将对象的键作为数组获取并使用内置于数组的forEach
函数:
Object.keys(json.shops).forEach(function(element, arrayIndex, array) {
console.log(array[element].name);
});