Dynamically Convert JSON to HTML Table Using JavaScript

← PrevNext →

JSON, or JavaScript Object Notation, is a simple and easy-to-understand data format. It is lightweight and language-independent, making it a popular choice for data interchange. In this article, I will demonstrate how to convert JSON data into an HTML table using JavaScript. Additionally, you will learn how to dynamically create a table in JavaScript using the createElement() method.

🚀 Check if data is a valid JSON or not.

Convert JSON to HTML Table using JavaScript

See this demo

The JSON

The JSON for this example looks like this.👇 Its has a list of three different books with ID, Name, Category and Price. Just three records for the example. You can add more.

Note: You can also use jQuery to convert data from a JSON file to an HTML table

[
    {
        "Book ID": "1",
        "Book Name": "Computer Architecture",
        "Category": "Computers",
        "Price": "125.60"
    },
    {
        "Book ID": "2",
        "Book Name": "Asp.Net 4 Blue Book",
        "Category": "Programming",
        "Price": "56.00"
    },
    {
        "Book ID": "3",
        "Book Name": "Popular Science",
        "Category": "Science",
        "Price": "210.40"
    }
]

Check if the above JSON is valid or not.

I want the program to read JSON data, get the columns (Book ID, Book Name etc.) for <table> header, and the values for the respective headers.

How to use async and await to fetch JSON from a file and convert the data into an HTML table
Dynamically add or remove Table rows in JavaScript and save data into a database
How to create a simple CRUD application using pure JavaScript

Popular: How to convert XML data (extracted from a file) to an HTML table using JavaScript async and await

🚀 Do you know you can convert your Excel data into JSON in a flash using JavaScript? Check this out. Its not a plug-in or a third party tool. Just plain JavaScript.

The Markup and the Script

In the markup section, I have a button to call a JavaScript function, which will extract the JSON data from the array, create a <table> with header and rows dynamically and finally populate the data in it. I also have DIV element that will serve as a container for our table. After I populate the data, I’ll append the <table> to the <div>.

<!DOCTYPE html>
<html>
<head>
    <style>
        table, th, td 
        {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th { 
            font-weight:bold;
        }
    </style>
</head>
<body>
    <input type='button' onclick='tableFromJson()' value='Create Table from JSON data' />
    <p id="showData"></p>
</body>

<script>
  let tableFromJson = () => {
    // the json data.
    const myBooks = [
      {'Book ID': '1', 'Book Name': 'Challenging Times',
       'Category': 'Business', 'Price': '125.60'
      },
      {'Book ID': '2', 'Book Name': 'Learn JavaScript',
       'Category': 'Programming', 'Price': '56.00'
      },
      {'Book ID': '3', 'Book Name': 'Popular Science',
       'Category': 'Science', 'Price': '210.40'
      }
    ]

    const table = document.createElement("table");    // Create table element.
    let tr = table.insertRow(-1);                   // table row.

    // Extract value for table headers. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
    let col = Object.keys(myBooks[0]);
    console.log(col);

    col.forEach((item) => {
      let th = document.createElement("th");      // table header.
      th.innerHTML = item;
      tr.appendChild(th);
    });

    // add json data to the table as rows.
    myBooks.forEach((item) => {
      tr = table.insertRow(-1);

      let val = Object.values(item);

      val.forEach((element) => {
        let tabCell = tr.insertCell(-1);
        tabCell.innerHTML = element;
      });
    });

    // Finally, add the newly created table with json data, to a container.
    const divShowData = document.getElementById('showData');
    divShowData.innerHTML = "";
    divShowData.appendChild(table);
  }
</script>
</html>
Try it

The JSON data is stored in an array named myBooks. The structure is straightforward, allowing for easy addition of more data.

First, it creates a table element using createElement() method.

Next, it creates headers (or columns) for the table by extracting first key index (like book id, book name etc.) from the JSON array and stores each key in an array named "col". It iterates through each item in the "col" array and uses them to create header to the table.

Remember, JSON objects are a collection of key and value pairs within curly brases. Each key is enclosed in double quotes followed by a : colon.

let col = Object.keys(myBooks[0]);
console.log(col);  // Output: (4) ['Book ID', 'Book Name', 'Category', 'Price']

col.forEach((item) => {
  let th = document.createElement("th");      // table header.
  th.innerHTML = item;
  tr.appendChild(th);
});

Finally it adds the JSON data to the table. It iterates (or loops) through each item in myBooks array, creates a new row (for the table), get values and create table cells.

// add json data to the table as rows.
myBooks.forEach((item) => {
    tr = table.insertRow(-1);

    let val = Object.values(item);

    val.forEach((element) => {
      let tabCell = tr.insertCell(-1);
      tabCell.innerHTML = element;
    });
});
See this demo

At the end, we'll simply add the newly created <table> to a container (a DIV element). That’s it. Hope you find this example useful.

← PreviousNext →