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": ""
    }
]
}
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. Commented Dec 10, 2013 at 0:57
  • FYI, you can use $.map to build the Array a little more cleanly. Here's a demo: jsfiddle.net/Bxrnq Commented Dec 10, 2013 at 1:03

2 Answers 2

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>" );
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.