Display JSON data in HTML table using JavaScript

Updated: 06-Apr-2022 | Tags: Javascript and JSON | Views: 17944

Introduction

Hello everyone, in this article we are going to fetch data from a JSON file, and we are going to display them in an HTML table with JavaScript. Let me quick explain what we are going to do.

We have some products stored in a JSON file. We are going to use the Fetch API to get those products from the JSON file. And we are going to put them in an HTML table. It's simple and easy.

Project folder

  • Let's walk through our projects structure.
  • Inside our root folder we have a product-images folder, where the images of our products are stored. Every image is associated with a product in the JSON file.
  • We have an index.html file.
    This is our home page where we are going to have the HTML table.
  • There is a products.json file. Our products are stored in that file.
  • We have a script.js file. This is our javascript file.
  • And a style.css file, where we have the css to style the html table. I am not going to analyze this file. It's not relevant to this article. But if you download the source code you will get the css file to.
Image of a project's folder in sublime text

The products.json file

This is how the products look like in the JSON file. Every product is an object. And objects have properties.
The properties here are the id, image, name, price, inventory, and productCode.
Later (in the javascript code), you will see that we target those properties to get the products values.

[
	{
		"id": 1,
		"image": "product-images/bike-1.jpeg",
		"name": "Orient Vita Pro 28\"",
		"price": "284.00",
		"inventory": 4,
		"productCode": "K203"
	},
	// Six more products are following.

The HTML file

Let's see what we have in the index file.
Inside the body tags i have a table element divided in two sections.
There is a table-header "thead", and a table body "tbody".

<body>
	<table>
		<thead>
			<tr>
				<th>Image</th>
				<th>Product name</th>
				<th>Price</th>
				<th>inventory</th>
				<th>Product code</th>
			</tr>
		</thead>
		<tbody id="data-output">
			<!-- Prodcuts from javascript file in here. -->
		</tbody>
	</table>

	<script src="script.js"></script> <!-- Link to the javascript file -->
  • From line 3-11 we have the table-head, and in line 12-14 we have the table-body.
  • In the table-head we have the names of the product's properties.
  • And the table-body is our placeholder which will be populated from the javascript file.
    The table-body has also an id of "data-output" so we can target the element from the javascript file.
  • And last in line 17 there is a script tag which links to the javascript file.

The JavaScript file

Now in the javascript file we are gonna use the fetch method, to fetch the products from the JSON file. When we have the products we are going to display each one in a table-row template.

fetch("products.json")
.then(function(response){
	return response.json();
})
.then(function(products){
	let placeholder = document.querySelector("#data-output");
	let out = "";
	for(let product of products){
		out += `
			<tr>
				<td> <img src='${product.image}'> </td>
				<td>${product.name}</td>
				<td>${product.price}</td>
				<td>${product.inventory}</td>
				<td>${product.productCode}</td>
			</tr>
		`;
	}

	placeholder.innerHTML = out;
});

Code breakdown

Let's analyze the javascript code line by line.

  • In line 1 we use the fetch() method to get the data from the products.json file.
    fetch("products.json")
  • The fetch() method returns a Promise object. So in line 2 we use the .then() method to catch the Response object and to resolve it to a javascript object with the .json() method, in line 3.
    .then(function(response){
    	return response.json();
    })
    		
  • The .json() method returns also a promise, so we have to use another .then() method to catch our data (in our case the products). That is what we do in line 5. The products argument inside the function is holding a javascript array of products.
    .then(function(products){
  • In line 6 we are targeting the table-body in the html file and we storing it in the placeholder variable.
    	let placeholder = document.querySelector("#data-output");
  • In line 7 we initialize a variable named out and we are setting its value to an empty string, so we can use the out variable later in the script.
    	let out = "";
  • Next we are going to loop through the products array in line 8 so we can access every product.
    	for(let product of products){
  • Inside the for loop, we use the out variable to append a table-row template which holds the product values. We are using a template literal (the back ticks ``) to write the html code.
    	out += `
    			<tr>
    				<td> <img src='${product.image}'> </td>
    				<td>${product.name}</td>
    				<td>${product.price}</td>
    				<td>${product.inventory}</td>
    				<td>${product.productCode}</td>
    			</tr>
    		`;
    	}
    		
  • We can insert in the html code, javascript variables using this structure ${product.image}.
  • And the last thing we have to do is to target the tbody element and add the data that the out variable holds.
    	placeholder.innerHTML = out;
    });
    		

The result

Running the above code in the browser you will get the following result. You have also to download the css to get the exact same style. Click on the "Get source code button"

image of an html table with products from a full stack development api

Summary

In this article we saw how to fetch data from a JSON file and display them in an HTML table using AJAX.

Source code

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.


You can download the source code and use it in any way you like.

Times downloaded: 4590

View on Youtube

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Comment section

You can leave a comment, it will help me a lot.

Or you can just say hi. 😉

Tutorial Categories