jQuery to display/load images received from JSON file

Today, I needed to display images received from a JSON file. The JSON file has only the path of the images. So in this post, find jQuery code to display or load images received from JSON file.

Related Post:

Consider, below is the JSON file content. It has products list with name and its image path.
{
   "products": [
      {
         "name": "Levis Blue Denim",
         "imgPath": "images/prods/levisbluedemin01.jpg"
      },
      {
         "name": "Pepe Black Jeans",
         "imgPath": "images/prods/pepeblackjeans01.jpg"
      },
      {
         "name": "Pepe Blue Jeans",
         "imgPath": "images/prods/pepebluejeans01.jpg"
      }
  ]
}
First, read the JSON file using $.getJSON function and then iterate through the received json result. Within the loop, fetch the imgPath property value, set it as image source to <img> tag and append it to a variable.

And once all the products are processed then add the variable value to DOM element in which images needs to be displayed.
$(document).ready(function () {
  var jsonURL = "productList.json";
  $.getJSON(jsonURL, function (json) 
  {
    var imgList= "";

    $.each(json.products, function () {
      imgList += '<li><img src= "' + this.imgPath + '"></li>';
    });

   $('#dvProdList').append(imgList);
  });
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..