Show Images from URLs in a JSON file using JavaScript

← PrevNext →

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

See this link. Its a sample JSON file with few objects in it. The image object has url for the images.

You can copy the JSON and save it in a file with .json extention.

You may also like this article: How to convert a JSON String to JSON Object in JavaScript

The Markup

In the markup section, I have a button, which when clicked calls a function. There is also a DIV element where the output (or the images) are displayed.

<html>
<body>
  <p>
    <input type="button" 
        onclick="showDataWithImages()" 
            value="Show Images" />
  </p>
  
  <div id='container'></div>
</body>  
</html>
The Script
<script>
  let showDataWithImages = () => {
    const 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) {
      let arrItems = [];
      arrItems = JSON.parse(json); 	// Populate array with JSON data.

      // The parent <div>.
      let div = document.getElementById('container');     
      div.innerHTML = '';

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

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

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

        let 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>
Try it

Note: 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.

👉 Do you know you can add a Text to an Image and save the image using plain JavaScript? Check out this example.
Add text to image using CSS and JavaScript

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 is done, I am appending the data, along the dynamically created elements to the parent element (a <div>).

Thanks for reading .

← PreviousNext →