Reputation: 349
I know this may seem basic to some of you, but I am trying to iterate a json object. I apologize as I seem to be having difficulty getting various examples to work. I've also read the jQuery documentation and the json examples listed there don't quite match my json structure.
Here's a link to my example which is displaying "null" in the console where I expected to see "1". I'm just trying to print out the article_id element of each "node" in the json array.
var json = [
[{
"article_id": 1,
"article_title": "test",
"article_content": "test1"
}, {
"article_id": 2,
"article_title": "test2",
"article_content": "this is a second test article"
}]
];
$.each(json, function (arrayID, group) {
console.log(group.article_id);
});
Upvotes: 1
Views: 1918
Reputation: 191799
You have an array nested inside of another array. You may want to take a look at how your JSON is being output, but in the meantime it's solved easily by another level of iteration:
$.each(json, function (arrayID, group) {
$.each(group, function (arrayID, group) {
console.log(group.article_id);
});
});
I've created a script that will allow you to see paths to values in JSON as well: http://jsfiddle.net/ExplosionPIlls/zEBZr/1/
Upvotes: 1
Reputation: 27568
Your object 'json' is an array with 1 element, which is itself an array of 2 elements. If your change your example to:
var json = [
{ "article_id": 1,
"article_title": "test",
"article_content": "test1" },
{ "article_id": 2,
"article_title": "test2",
"article_content": "this is a second test article" }
];
Then it produces the articles ids: 1,2.
If you need to iterate over a two dimensional array, then you can use a nested loop:
$.each(json, function (idx1, entry) {
$.each(entry, function (idx2, group) {
console.log(group.article_id);
});
});
Upvotes: 1
Reputation: 3534
Your json is not an array of object, it is an array of array of object.
When you enter in your iteration, for each element, the arrayID is the index (0, 1, etc...) and the group is the sub array.
To solve your problem, use json[0] instead of json in your code
$.each(json[0], function (arrayID, group) {
console.log(group.article_id);
});
Upvotes: 5