开发者

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, funct开发者_运维知识库ion (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);
    });​
});


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


use for in construction

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


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/


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜