views:

735

answers:

1

I would like to interpret data from JSON feed using jQuery getJSON.

$(function() {
    $.getJSON('http://gdata.youtube.com/feeds/users/raywilliamjohnson/uploads?alt=json-in-script&callback=showMyVideos2&max-results=30', function(data) { 
        $.each(data.feed.entry, function(i, item) {
            updated = item.updated;
            url = item['media$group']['media$content']['url'];
            thumb = item['media$group']['media$thumbnail'][0]['url'];
            numViews = item['yt$statistics']['viewCount'];
        });
    });
});

How to correctly interpret JSON data and assign variables to data items (ex. url, numViews, etc...)? Thanks much in advance for any help.

+2  A: 

You need to set the callback GET parameter to ? (callback=?), so jQuery will be able to make the JSONP request correctly and execute your callback.

Also to get the url, you need to access the item at index [0], just like you get the thumb:

$(function() {
    $.getJSON('http://gdata.youtube.com/feeds/users/raywilliamjohnson/uploads?alt=json-in-script&callback=?&max-results=30', function(data) { 
        $.each(data.feed.entry, function(i, item) {
            var updated = item.updated;
            var url = item['media$group']['media$content'][0]['url'];
            var thumb = item['media$group']['media$thumbnail'][0]['url'];
            var numViews = item['yt$statistics']['viewCount'];
            // ...
        });
    });
});

Check an example here.

CMS
An important note is the addition of `var`
Justin Johnson
@Justin: Thanks, I forgot to mention it, just for the record, if you make an assignment (you miss the `var` statement) to an undeclared identifier (one that is not reachable in the scope chain), it will become member of the global object (a global variable) something that you don't really want or need...
CMS
Great point CMS. Thanks to both of you.