0

I am try access an Object array using getJson, I've tried many things but I keep getting an 'undefined' or [Object, object] returned.

$.getJSON( "js/test.json", function( data ) {
    var items = new Array();
    $.each( data, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
    });

    $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
    }).appendTo( "body" );
});

Here is the JSON, I am trying to get the 'title' of each 'entries'.

{
"$xmlns": {
    "pl1": "url"
},
"startIndex": 1,
"author": "MJS",
"entries": [
    {
        "title": "This is target",
        "m$ct": [
            {
                "m$name": "name"
            }
        ],
        "m$rt": "pd",
        "m$content": [
            {
                "plfile$width": 640
            },
            {
                "plfile$width": 960
            }
        ],
        "plm$c": [],
        "link": ""
    },
    {
        "title": "title2",
        "m$ct": [
            {
                "m$name": "name"
            }
        ],
        "m$rt": "pd",
        "m$content": [
            {
                "plfile$width": 640
            },
            {
                "plfile$width": 960
            }
        ],
        "plm$c": [],
        "link": ""
    }
]
}
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
Randall987
  • 15
  • 1
  • 2
  • 3
    Seems like you should be iterating `data.entries` instead of `data`. Then you'd use `val.title` instead of `val.entries.title`. Not sure what you expect the ID of the `li` to be though. If that should be the index number, then `key` would be fine there. – Blue Skies Dec 10 '13 at 00:57
  • FYI, you can use `$.map` to build the Array a little more cleanly. Here's a demo: http://jsfiddle.net/Bxrnq/ – Blue Skies Dec 10 '13 at 01:03

2 Answers2

2
$.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});

should instead read:

$.each( data.entries, function( key, entry ) {
    items.push( "<li id='" + key + "'>" + entry.title + "</li>" );
});
Patrick Gunderson
  • 3,263
  • 17
  • 28
0

You're iterating over the whole json instead of the entries

It should be data.entries in the each and then just val.title

$.getJSON( "js/test.json", function( data ) {
    var items = new Array();
    $.each( data.entries, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val.title + "</li>" );
    });

    $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
    }).appendTo( "body" );
});
Lenny
  • 5,663
  • 2
  • 19
  • 27