Possible Duplicate:
How do I enumerate the properties of a javascript object?
{
347655082: {
album:{
title: "A",
genre: "Pop",
}
},
347655083: {
album:{
title: "B",
genre: "Rock",
}
}
}
Normally the "outside" key is the same, so I can easily target the nested objects. In the case the "outside" key is variable which can be anything.
albums = JSON.parse(json); //parse json storing it in albums
I cannot run a foreach on albums, say "albums has not method foreach".
albums.forEach(function(album, i){
}
You can only use .forEach()
on arrays. Your albums
entity is an Object
so you should use for ... in ...)
for (var key in albums) {
if (albums.hasOwnProperty(key)) {
// do something with albums[key]
...
}
}
For code targetting node.js or any other ES5 implementation you could probably omit the if
clause - it's only needed if you've got code that has unsafely added stuff to Object.prototype
.
ES5 has a great method for iteration object own enumerable properties - Object.keys(obj). I prefer the following iteration method:
Object.keys(albums).forEach(function (key) {
console.log(albums[key]);
});
That's not valid json The valid json would be:-
{
"347655082": {
"album": {
"genre": "Pop",
"title": "A"
}
},
"347655083": {
"album": {
"genre": "Rock",
"title": "B"
}
}
}
keys in json need to be double quoted as shown.
To validate json checkout jsonlint.com