J K
J K

Reputation: 349

Iterating through a json array of objects using jquery

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.

http://jsfiddle.net/zZjfj/1/

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

Answers (3)

Explosion Pills
Explosion Pills

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);
    });
});

http://jsfiddle.net/zZjfj/2/

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

Kyle Burton
Kyle Burton

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

MatRt
MatRt

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

Related Questions