JavaScript: Displaying JSON data as a table in HTML

Updated: February 4, 2024 By: Guest Contributor Post a comment

Introduction

In this tutorial, we’ll explore how to display JSON data in an HTML table using JavaScript. JSON, or JavaScript Object Notation, is a lightweight format for storing and transporting data, making it ideal for web applications. Extracting JSON data and displaying it on a web page in a human-readable format is a common task, and doing so effectively can enhance the user experience.

Let’s dive into the details and learn how to dynamically generate an HTML table populated with JSON data using plain JavaScript. We’ll walk through the steps, from fetching the JSON data to iterating over it and creating a table dynamically.

Prerequisites

  • Basic understanding of HTML and JavaScript.
  • A sample JSON file/data or API endpoint that returns JSON.

Step-by-Step Instructions

Step #1 – Understanding Your JSON Data

First, let’s consider a sample JSON object that we’ll be working with:

{
  "employees": [
    { "name": "John Doe", "age": 30, "position": "Software Engineer" },
    { "name": "Jane Doe", "age": 25, "position": "Project Manager" }
  ]
}

This sample JSON represents a collection of employees, each with their name, age, and position. Our goal is to display this information in a table on our webpage.

Step #2 – Fetching JSON Data

If the JSON data is stored in a local file or obtained from an API, we need to fetch it using JavaScript. Here’s a basic example of how to do so using the Fetch API:

fetch('path/to/your/json/data.json')
  .then(response => response.json())
  .then(data => {
    // Call function to display table
    createTable(data.employees);
  })
  .catch(error => console.error('Error:', error));

In this example, we’re fetching the JSON data from a specified path, parsing it as JSON, and then passing it to a function createTable that will generate our HTML table.

Step #3 – Creating the HTML Table

Next, we’ll write the createTable function that creates an HTML table dynamically with the fetched data:

function createTable(data) {
  const table = document.createElement('table');
  const tableHead = document.createElement('thead');
  const tableBody = document.createElement('tbody');

  // Append the table head and body to table
  table.appendChild(tableHead);
  table.appendChild(tableBody);

  // Creating table head
  let row = tableHead.insertRow();
  Object.keys(data[0]).forEach(key => {
    let th = document.createElement('th');
    th.textContent = key.toUpperCase();
    row.appendChild(th);
  });

  // Creating table body
  data.forEach(item => {
    let row = tableBody.insertRow();
    Object.values(item).forEach(value => {
      let cell = row.insertCell();
      cell.textContent = value;
    });
  });

  // Append the table to the HTML document
  document.getElementById('yourElementId').appendChild(table);
}

This function takes the array of employee data, creates a table, and dynamically fills it with rows and columns based on the JSON data received. We iterate over the array of data to create each row in the table body and over the keys of the first object to create the table headers.

Step #4 – Styling Your Table

While the table is now functional, applying some CSS can significantly improve its appearance. Here’s a simple style example:

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

You can further customize the style according to your application’s design. Styling is essential for making the data clear and easily readable by users.

Conclusion

Displaying JSON data in an HTML table is a common yet essential task in web development. By following the steps outlined in this tutorial, you now know how to fetch JSON data, parse it, and dynamically display it in a table using plain JavaScript. Moreover, with the basic styling tips provided, you can ensure that the table not only serves its function but is also visually appealing.

Whether you’re displaying a small amount of data or have to manage large datasets, these techniques will be instrumental in presenting the information in an accessible and organized manner. As you become more comfortable with these concepts, you can optimize and expand upon them to suit the specific needs of your projects.