Tunde Dev
Tunde Dev

Reputation: 13

Get data from URL that returns JSON using JQuery

I have been struggling with trying to parse this JSON that is returned from a url but with no luck

[
    {
        "books": [
        {
            "date_added":"Tue, September 23, 2014",
            "id":"3253678",
            "cover":"3253678.jpg",
            "title":"Walking",
            "author":"Henry David Thoreau",
            "authorid":"3"},
        {
            "date_added":"Mon, September 15, 2014",
            "id":"23477675",
            "cover":"23477675.jpg",
            "title":"Major Barbara",
            "author":"George Bernard Shaw",
            "authorid":"4"
        }]
    }
]

Here is my JQuery

$.getJSON(url).done(function(data) {
        $.each(data.books, function( i, ele) {
            alert(ele.title);
        });
    });

Any help will be appreciated. Cheers guys

Upvotes: 0

Views: 64

Answers (3)

Eric Chavez
Eric Chavez

Reputation: 55

This should work

$.each(data[0].books, function(i, ele) {
  alert(ele.title);
});

Upvotes: 0

Cesar Villasana
Cesar Villasana

Reputation: 687

I think you are missing that the main JSON structure is an Array, which has objects that only have one field called "books" which is an array as well.

You need to first iterate on the main structure and in each item get the books, and then for each book (another iteration, get the titles).

To have a better look at your Json Structure, Paste the String content in:

http://json.parser.online.fr/

There you can see the whole structure itself

Cheers!

Upvotes: 0

David Hammond
David Hammond

Reputation: 3306

The data is actually an array with one item, which is an object. So you can try:

$.each(data[0].books ....

Upvotes: 2

Related Questions