Search code examples
javascriptjsongoogle-custom-search

Grab JSON image in custom search


how do i grab the image from a Custom search JSON response?

  function hndlr(response) {
  for (var i = 0; i < response.items.length; i++) {
    var item = response.items[i];
    document.getElementById("content").innerHTML += "<br>" + item.htmlTitle;
  }
}

for example, i already have 10 results, every article having a title, description and image.

I have already connected to the API with my key and CX code, accessed the htmlTitle, or link or other components. but i dont know how to access the thumbnail part where my image is bound to each result.

this is the response from google custom search: https://drive.google.com/open?id=101MuxGd8oyOAYvfNthuW7saNpm-m3kSe

How do i access thumbnail.src?

item.pagemap.thumbnail.src???

Thanks for your help


Solution

  • as thumbnail is an array of objects, you can access it on the following way if item is an element from the items array:

    item.pagemap.thumbnail[0].src
    

    where item.pagemap.thumbnail[0] is the first object from the thumbnail array.

    To make it more bulletproof you should check the array length before fetching the first element from it and also that the src attribute is exist or not. For example:

    var fallbackImage = 'the url for the fallback image';
    var thumbnail = item.pagemap.thumbnail.length > 0 ? item.pagemap.thumbnail[0].src || fallbackImage : fallbackImage;