How to Display Images Retrieved from a JSON File using jQuery

← PrevNext →

If you are a JavaScript enthusiast, then you must check my previous post where I have explained it using a different and yet simple technique. Here however, I am sharing a jQuery example that explains how easily you can display images on a web page using image URLs retrieved from a JSON file.

You can use a JSON format to store and transfer a variety of data. Other than simple text data, you can also store URLs of images. For example,

[  { "Image": "https://www.encodedna.com/images/theme/angularjs.png" } ]

In the above JSON array, the object “Image” has a URL of an image. This data can be stored in a JSON file.

See this demo

You can easily retrieve data from a JSON file using jQuery. Here’s one post that explains how.

Now, let’s find out how we can show these images, extracted from a JSON file (with some other data), in an HTML <table> using jQuery.

Create JSON Data

I have JSON array with three different objects, ID, Name and Image. Copy the below data and paste it in a Notepad. Save the file as data-with-image.json.

[
    {
        "ID": "001",
        "Name": "Angular", 
        "Image": "angularjs.png" 
    },
 
    {
        "ID": "002",
        "Name": "JSON", 
        "Image": "json.png" 
    },
  
    {
        "ID": "003",
        "Name": "Asp.Net", 
        "Image": "aspnet.png" 
    }
]
The Markup
<html>
<head>
    <title>Show Image from JSON using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <style>
        table 
        {
            width: 300px;
            font: 17px Calibri;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        table img 
        {
            border: none;
            width: 51px;
            height: 51px;
        }
    </style>
</head>
<body>
    <p><input type="button" onclick="imagesFromJSON()" value="Show Images" /></p>
    <div id='showData'></div>
</body>

I have defined the CSS style for my HTML <table> and for assigning the image width and height. You can ignore it if you want.

Now the Script
<script>
    $(document).ready(function () {
        $.getJSON("data-with-image.json", function (data) {

            var arrItems = [];      // The array to store JSON items.
            $.each(data, function (index, value) {
                arrItems.push(value);       // Push values in the array.
            });

            // Extract values for the table header.
            var col = [];
            for (var i = 0; i < arrItems.length; i++) {
                for (var key in arrItems[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // Create a <table> element dynamically.
            // Ref: https://www.encodedna.com/javascript/populate-json-data-to-html-table-using-javascript.htm 
            var table = document.createElement("table");

            var tr = table.insertRow(-1);                   // Table row.

            for (var i = 0; i < col.length; i++) {
                var th = document.createElement("th");      // Table header.
                th.innerHTML = col[i];
                tr.appendChild(th);
            }

            // Add JSON data to the table as rows.
            for (var i = 0; i < arrItems.length; i++) {
                tr = table.insertRow(-1);

                for (var j = 0; j < col.length; j++) {
                    var tabCell = tr.insertCell(-1);
                    if (j === 2) {      // The last JSON column has image urls.

                        // Create an <img> element to show the images.
                        var img = document.createElement('img');        
                        img.src = arrItems[i].Image;   // The image source from JSON array.
                        tabCell.appendChild(img);
                    }
                    else
                        tabCell.innerHTML = arrItems[i][col[j]];
                }
            }

            // Finally, add the newly created <table> with data to a container.
            var divContainer = document.getElementById("showData");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);
        });
    });
</script>
</html>
Try it

The $.getJSON() method is used to get JSON data from a remote location using an Ajax HTTP Get request. I have used the method in the beginning of my script. The method takes a parameter in the form of a URL of the JSON file.

Once the JSON data is retrieved, I am storing the data in an array.

var arrItems = [];              // The array to store JSON items.
$.each(data, function (index, value) {
    arrItems.push(value);       // Push values in the array.
});

Along with other data, the array also has the image URLs. To show the text values (such as the name and id) I can use the elements innerHTML property. However, to display the images using the URLs, I have to first create an <img> element (for each record in the JSON file), and assigning the URL as source to the <img> elements, which is then added to a <table> cell.

var img = document.createElement('img');        // Create an <img> element.
img.src = arrItems[i].Image;                    // The image source from JSON array.
tabCell.appendChild(img);

Well, that’s it. Thanks for reading .

See this demo

← PreviousNext →