Search code examples
javascriptjqueryjsontwitch

Parsing JSON within JSON with jQuery


I am using the Twitch API and am attempting to pull follower images. To do this, I have to parse my most recent followers, take the name of these followers and make a request for each to obtain their user image.

$.getJSON(streamFollowers, function(json) {

for (var i = 0; i < 5; i++) {
  var followerDisplayName = json.follows[i].user.display_name;
  var followerName = json.follows[i].user.name;
  var followerJSON = 'https://api.twitch.tv/kraken/channels/' + followerName + '';

$.getJSON(followerJSON, function(json) {
  var followerImage = json.logo;
  if (followerImage === "null") {
    followerImage = "null.jpg";
  };
});

What I am having difficulty with is attempting to pull the "followerImage" result from the "followerJSON" parse.

Heres the code in action. http://codepen.io/anon/pen/rxEPXQ

Edit: A second parse isn't required. You can pull user images from the initial parse for usernames etc. I just didn't see see it at the time. My bad.


Solution

  • A users logo is null if a user doesn't have a profile picture set.

    http://codepen.io/anon/pen/EPBMox?editors=1011

    here it is with all your followers, you can see ones with it set work properly.

    var streamFollowers = "https://api.twitch.tv/kraken/channels/tsm_dyrus/follows";
    $.getJSON(streamFollowers, function(json) {
      for (var i = 0; i < json.follows.length; i++) {
        var followerDisplayName = json.follows[i].user.display_name;
        var followerName = json.follows[i].user.name;
        var followerImage = json.follows[i].user.logo;
        $('#followers').append('<li><img src="' + followerImage + '"></img><br />' + followerDisplayName + '</li>');
      }
    });