George150
George150

Reputation: 25

Parse Giphy API JSON in Javascript

I would like to parse a response from the api giphy using Javascript I would like to get the downsized url of all the images using the Giphy API

Here is what the json response looks like
http://www.jsoneditoronline.org/?id=bbd7b24363fb7fa5035c22059b392bd7

Here is my code that doesn't work that well

const url = `http://api.giphy.com/v1/gifs/search?q=cat&api_key=dc6zaTOxFJmzC`;
            var xhr = new XMLHttpRequest();
            xhr.onload = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = JSON.parse(xhr.responseText);
                    var data = response.data;
                    for (var i in data) 
                        console.log(i.url);
                }
            }
            xhr.open('GET', url, true); 
            xhr.send();
          } 

Upvotes: 1

Views: 1134

Answers (3)

Jeff A
Jeff A

Reputation: 72

You can use the map prototype function and parse each object in the data array like so.

const url = `http://api.giphy.com/v1/gifs/search?q=cat&api_key=dc6zaTOxFJmzC`;
var xhr = new XMLHttpRequest();
xhr.onload = function() {

  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);
    var data = response.data;

    data.map(function(image) { // image = current object in array
      console.log(image.images.downsized.url);  // parse downsized url from current object in array     
    })

  }
}
xhr.open('GET', url, true);
xhr.send();

Working example in codepen

Upvotes: 0

bstockwell
bstockwell

Reputation: 514

You can use a very simple reduce function to get the array:

var result = response.data.reduce((prev,curr) => {
    return prev.concat(curr.images.downsized.url)
},[])

Upvotes: 0

Adam.M
Adam.M

Reputation: 124

I had to use this api for a homework assignment a couple of months ago. Looping through your response like this will log all of the downsized image urls to the console.

     var data = response.data;

     for(var i=0; i < data.length; i++){

         console.log(data[i].images.downsized.url);

     }

Upvotes: 4

Related Questions