tuddy
tuddy

Reputation: 1834

Parsing JSON array within array

I have the following code that gets the first 'name' in an array called 'feeds' within my JSON, I would like to now loop through the JSON and get each name. I haven't been able to get that loop to work.

JSON:

{
    "title": "Testing",
    "created_at": "2011-10-05T16:23:26.217Z",
    "feeds": [{
        "0": {
            "name": "twitter",
            "key": "person1"
        },
        "1": {
            "name": "twitter",
            "key": "person2"
        },
        "_id": "4e8c847e02edc10035000003"
    }]
}

This gets the first title successfully:

$.getJSON(getthisshit, function (myJson) {
    var myfeed = myJson.feeds[0][0].name;
    alert(myfeed);
});

I tried to loop through doing something like this, but have not been able to get it to work:

$.getJSON(getthisshit, function (myJson) {
    $.each(myJson.feeds, function (i, item) {
        alert(item.name);
    });​
});

Upvotes: 1

Views: 590

Answers (4)

verybadbug
verybadbug

Reputation: 929

use for in construction

for (var i in json.feeds[0]) alert(json.feeds[0][i].name);

Upvotes: 0

Guffa
Guffa

Reputation: 700830

The problem with that data is that the feeds property is an array, but it's not used as an array, and it contains an object that looks kind of like an array, but isn't.

The properties named 0 and 1 in the object have objects with name properties, but the property named _id is not an object at all, and thus have no name property.

I suggest that you change the data to something like this, where the feeds array is used like an array, and where the _id property is not inside an object along with other properties that have names that are numbers:

{
  "title": "Testing",
  "created_at": "2011-10-05T16:23:26.217Z",
  "feeds": [
    {
      "name": "twitter",
      "key": "person1"
    },
    {
      "name": "twitter",
      "key": "person2"
    }
  ],
  "_id": "4e8c847e02edc10035000003"
}

With this data your code will work as it is, and you won't get an undefined value when you try to read the name property from the _id string.

Upvotes: 0

Akos Lukacs
Akos Lukacs

Reputation: 2047

To iterate over all elements, and write to console:

$.each(myJson.feeds, function (i, item) {
    $.each(item, function(i, elem){
        console.log('name: ' + elem.name + ', key: ' + elem.key);
    });
});

Try it in JSFiddle: http://jsfiddle.net/CUfnL/

Upvotes: 0

phihag
phihag

Reputation: 288270

Your solution is nearly correct, you're just iterating over feeds instead of feeds[0]:

$.getJSON(getthisshit, function (myJson) {
    $.each(myJson.feeds[0], function (i, item) {
        //             ^^^
        alert(item.name);
    });​
});

Upvotes: 1

Related Questions