I try to loop this json but it is not working.I want to loop through the shops but it is not working
The 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"
}
}
}
The script
$.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);
}
});
This doesn't give me any results
3 Answers 3
json.shops isn't an array, it's an object. You can use a for..in loop or $.each
Using $.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);
});
});
Using 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);
}
8 Comments
value.name and value.id are undefined.As shown in the comments, shops is an object, not an array. You can loop through all the properties of a javascript object using:
$.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]);
}
});
Comments
json.shops.length is undefined, because shops is an object and not an array and doesn't (in this case) have a "length" property. but every JavaScript object can have properties, and those property names can be retrieved as a list, which you can then iterate over:
for(var i = 0; i < Object.keys(json.shops).length; i++){
console.log(json.shops[Object.keys(json.shops)][i].name);
}
or, alternately, fetch the object's keys as an array and use the forEach function built in to arrays:
Object.keys(json.shops).forEach(function(element, arrayIndex, array) {
console.log(array[element].name);
});
1 Comment
Object.keys(json.shops)[i] will return a string key, not an object.
shopsis not an array. It is an object. stackoverflow.com/questions/684672/…console.log(json);and tell me what it is returning?