Display JSON data in HTML table using JavaScript

Updated: 06-Apr-2022 / Tags: Javascript and JSON / Views: 23400 - Author: George

Introduction

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

We have some products stored in a JSON file, and we will use the Fetch API to retrieve them and display them in an HTML table. It's a simple and easy task.

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

Project folder

|-- project-folder/
  |-- product-images/
    |-- bike-1.jpg
    |-- bike-2.jpg
        more images ...
  |-- index.html
  |-- products.json
  |-- script.js
  |-- styles.css
  • 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.

The products.json file

In our JSON file, we have an array of objects. Each object represents a product and contains the following properties: id, image, name, price, inventory, and productCode. Later in the JavaScript code, you will see that we target these properties to retrieve the values of each product.

[
	{
		"id": 1,
		"image": "product-images/bike-1.jpeg",
		"name": "Orient Vita Pro 28\"",
		"price": "284.00",
		"inventory": 4,
		"productCode": "K203"
	},
	{
		"id": 2,
		"image": "product-images/bike-2.jpeg",
		"name": "Orient S-400 26\"",
		"price": "198.00",
		"inventory": 14,
		"productCode": "K433"
	},
	{
		"id": 3,
		"image": "product-images/bike-3.jpeg",
		"name": "Bullet Bora 20\"",
		"price": "350.00",
		"inventory": 7,
		"productCode": "K012"
	},
	{
		"id": 4,
		"image": "product-images/guitar-1.png",
		"name": "Feder handmade",
		"price": "790.00",
		"inventory": 5,
		"productCode": "G0127"
	},
	{
		"id": 5,
		"image": "product-images/guitar-2.png",
		"name": "Ibanez G120",
		"price": "430.00",
		"inventory": 2,
		"productCode": "G1233"
	},
	{
		"id": 6,
		"image": "product-images/guitar-3.png",
		"name": "Feder Blues edition",
		"price": "650.00",
		"inventory": 6,
		"productCode": "G4478"
	}
]

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 going to use the fetch method to retrieve the products from the JSON file. Once we have the products, we will display each one using 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 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 CSS code

And last we have the css code to style the table.

*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body{
	font-family: sans-serif;
	min-height: 100vh;
	color: #555;
}

table{
	width:  1000px;
	margin: 30px auto;
}

table th{
	padding: 10px 0;
	background-color: #f4f4f4;
	/* background-color: #fff; */
	border:  thin solid #d4d4d4;
}

table td{
	padding: 10px;
	border:  thin solid #d4d4d4;
	width: 18%;
	text-align: center;
	background-color: #fff;
}

table img{
	width:  70%;
}
		

The result

Running the above code in the browser you will get the following result. You have also to download the css and the product images to get the exact same output. 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.

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.

Source code

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

Times downloaded: 5723

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. 😉