Show Images from URLs in a JSON file using JavaScript

You can use the XMLHttpRequest object in JavaScript to read and extract data from an external JSON file. I have explained this in detail in one of my previous posts. Now here in this post I am sharing an example that explains how to show images using image URLs extracted from a JSON file in JavaScript.

The JSON Data

Here’s a sample JSON data with the image URLs. It has 3 objects, the ID, Name and Image. The value for the Image object must have a URL (or the location of the files).

[
    {
        "ID": "001", 
        "Name": "Angular", 
        "Image": "angular.png"
    },
  
    {
        "ID": "002", 
        "Name": "JSON", 
        "Image": "json.png"
    },
  
    {
        "ID": "003", 
        "Name": "Asp.Net", 
        "Image": "aspnet.png"
    }
]

Open the Notepad and copy and paste the above data as it is. Save the file in .json format. I have named it data-with-image.json.

Related: How to Convert a JSON String to JSON Object in JavaScript

The Markup with the JavaScript Code
<html>
<head>
    <title>Show Image using URLs from JSON file using JavaScript</title>
    <style>
        #birds {
            width: 200px;
            text-align: center;
            overflow: hidden;
            padding: 3px;
            font: 14px Calibri;
            border:solid 1px #ddd;
        }
        #birds div {
            margin: 0;
            width: 49%;
            float: left;
            text-align: center;
        }
        
        #birds div img {
            border: none;
            width: 51px;
            height: 51px;
        }
    </style>
</head>
<body>
    <p><input type="button" onclick="showDataWithImages()" value="Show Images" /></p>
    <div id='birds'></div>
</body>
<script>
    function showDataWithImages() {

        var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

        function reportStatus() {
            if (oXHR.readyState == 4)               // Request completed.
                showTheList(this.responseText);     // All set. Now show the data.
        }

        oXHR.onreadystatechange = reportStatus;
        oXHR.open("GET", "../../library/data-with-image.json", true);   // true = asynchronous request, false = synchronous request.
        oXHR.send();

        function showTheList(json) {
            var arrItems = [];
            arrItems = JSON.parse(json); 	// Populate array with JSON data.

            var div = document.getElementById('birds');     // The parent <div>.
            div.innerHTML = '';

            // Loop through data in the JSON array.
            for (i = 0; i <= arrItems.length - 1; i++) {

                // Create two <div> elements, one for the name and the other to show the image.
                var divLeft = document.createElement('div');
                divLeft.innerHTML = arrItems[i].Name;

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

                var divRight = document.createElement('div');
                divRight.setAttribute('style', 'border-left: solid 1px #ddd;');
                divRight.appendChild(img);

                // Add the child DIVs to parent DIV.
                div.appendChild(divLeft);
                div.appendChild(divRight);

                // Note: Instead of <div>, you can also create a dynamic <table> to show the images. 
                // Here's an example ... https://www.encodedna.com/javascript/populate-json-data-to-html-table-using-javascript.htm 
            }
        }
    }
</script>
</html>
Try it

In the above example, I am using a <div> element to show the data with the images using image URLs extracted from the JSON file. You can use a <table> instead of <div> to show the data

I have explained in detail about the XMLHttpRequest object here. You must read the post to understand how the object works and how using its various property you can connect and extract data from different types of files in a remote location.

Remember: All modern browsers support the XMLHttpRequest object. Therefore, you can use this object and properties without any hesitation.

Now back to the code. Once the JSON file is received, the data is stored in an Array. This will make the data extraction process simple.

arrItems = JSON.parse(json); // Fill JSON data to an array.

Finally, I am running a loop to extract all the data from the array. To show the images on the web page, I am creating an <img> object and assigning the image url as the source to the <img> object.

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

See this line here … arrItems[i].Image. The object name, Image, is case sensitive. This object is defined in the JSON file. You must use it as it is in your script.

That’s it. When all done, I am appending the data, along the dynamically created elements to the parent element (a <div>).

Thanks for reading.

← PreviousNext →


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: