The Wayback Machine - https://web.archive.org/web/20241003014524/https://www.geeksforgeeks.org/how-to-convert-json-data-to-a-html-table-using-javascript-jquery/
Open In App

How to convert JSON data to a html table using JavaScript/jQuery ?

Last Updated : 19 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

To convert JSON data into an HTML table, there are multiple approaches, each of which has its own strengths. Let’s walk through both approaches you mentioned, detailing how each one works.

Approach 1: Using for loop

  • Take the JSON Object in a variable.
  • Call a function that first adds the column names to the < table > element. (It is looking for all columns, which is the UNION of the column names).
  • Traverse the JSON data and match the key with the column name. Put the value of that key in the respective column.
  • Leave the column empty if there is no value of that key.

Example: This example implements the for-loop approach.  

HTML
<!DOCTYPE HTML>
<html>

<head>
    <title>
        How to convert JSON data to a
        html table using JavaScript ?
    </title>

    <script src=
     "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
</head>

<body style="text-align:center;" id="body">

    <h1 style="color:green;">
        GeeksForGeeks
    </h1>

    <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
    </p>


    <button onclick="constructTable('#table')">
        click here
    </button>

    <br><br>

    <table align="center" id="table" border="1">
    </table>

    <script>
        let el_up = document.getElementById("GFG_UP");

        let list = [
            { "col_1": "val_11", "col_3": "val_13" },
            { "col_2": "val_22", "col_3": "val_23" },
            { "col_1": "val_31", "col_3": "val_33" }
        ];

        el_up.innerHTML = "Click on the button to create "
            + "the table from the JSON data.<br><br>"
            + JSON.stringify(list[0]) + "<br>"
            + JSON.stringify(list[1]) + "<br>"
            + JSON.stringify(list[2]);

        function constructTable(selector) {

            // Getting the all column names
            let cols = Headers(list, selector);

            // Traversing the JSON data
            for (let i = 0; i < list.length; i++) {
                let row = $('<tr/>');
                for (let colIndex = 0; colIndex < cols.length; colIndex++) {
                    let val = list[i][cols[colIndex]];

                    // If there is any key, which is matching
                    // with the column name
                    if (val == null) val = "";
                    row.append($('<td/>').html(val));
                }

                // Adding each row to the table
                $(selector).append(row);
            }
        }

        function Headers(list, selector) {
            let columns = [];
            let header = $('<tr/>');

            for (let i = 0; i < list.length; i++) {
                let row = list[i];

                for (let k in row) {
                    if ($.inArray(k, columns) == -1) {
                        columns.push(k);

                        // Creating the header
                        header.append($('<th/>').html(k));
                    }
                }
            }

            // Appending the header to the table
            $(selector).append(header);
            return columns;
        }       
    </script>
</body>

</html>

Output: 

ezgifcom-video-to-gif-(1)

Output

Approach 2: Using JSON.stringify() method

  • Store the JSON object into the variable. and first put all keys in a list.
  • Create an element <table> and a <tr> element for the header of the table.
  • Visit the keys list and create a <th> for each value and insert it into the <tr> element created for the header.
  • Then, for every entry in the object, create a cell and insert it to the particular row.
  • Leave the column empty if there is no value of that key.

Example: This example implements the JSON.stringify() method approach. 

HTML
<!DOCTYPE HTML>
<html>

<head>
    <title>
        How to convert JSON data to a html
        table using JavaScript/jQuery ?
    </title>

    <script src=
    "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
</head>

<body style="text-align:center;">

    <h1 style="color:green;">
        GeeksForGeeks
    </h1>

    <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
    </p>


    <button onclick="GFG_FUN()">
        click here
    </button>

    <br><br>

    <table id="table" align="center" border="1px"></table>

    <script>
        let el_up = document.getElementById("GFG_UP");

        let list = [
            {
                "col_1": "val_11", "col_2": "val_12",
                "col_3": "val_13"
            },
            {
                "col_1": "val_21", "col_2": "val_22",
                "col_3": "val_23"
            },
            {
                "col_1": "val_31", "col_2": "val_32",
                "col_3": "val_33"
            }
        ];

        el_up.innerHTML = "Click on the button to create the "
            + "table from the JSON data.<br><br>"
            + JSON.stringify(list[0]) + "<br>"
            + JSON.stringify(list[1]) + "<br>"
            + JSON.stringify(list[2]);

        function GFG_FUN() {
            let cols = [];

            for (let i = 0; i < list.length; i++) {
                for (let k in list[i]) {
                    if (cols.indexOf(k) === -1) {

                        // Push all keys to the array
                        cols.push(k);
                    }
                }
            }

            // Create a table element
            let table = document.createElement("table");

            // Create table row tr element of a table
            let tr = table.insertRow(-1);

            for (let i = 0; i < cols.length; i++) {

                // Create the table header th element
                let theader = document.createElement("th");
                theader.innerHTML = cols[i];

                // Append columnName to the table row
                tr.appendChild(theader);
            }

            // Adding the data to the table
            for (let i = 0; i < list.length; i++) {

                // Create a new row
                trow = table.insertRow(-1);
                for (let j = 0; j < cols.length; j++) {
                    let cell = trow.insertCell(-1);

                    // Inserting the cell at particular place
                    cell.innerHTML = list[i][cols[j]];
                }
            }

            // Add the newly created table containing json data
            let el = document.getElementById("table");
            el.innerHTML = "";
            el.appendChild(table);
        }    
    </script>
</body>

</html>

Output: 

ezgifcom-video-to-gif-(2)

Output

Both approaches are effective for converting JSON data to an HTML table. Depending on your needs and complexity of data, either approach can be used.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Similar Reads

Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
How to fetch data from JSON file and display in HTML table using jQuery ?
The task is to fetch data from the given JSON file and convert data into an HTML table. Approach: We have a JSON file containing data in the form of an array of objects. In our code, we are using jQuery to complete our task. The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two
3 min read
How to Convert HTML Table to JSON in JavaScript?
HTML tables are commonly used to present structured data on websites. In many scenarios, this tabular data needs to be converted to JSON format for processing, storage, or server communication. We will discuss different approaches to converting HTML tables to JSON using JavaScript. These are the following approaches: Table of Content Manual Travers
3 min read
Convert JSON String to Array of JSON Objects in JavaScript
Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information. There are two approaches to solving this problem, which are discussed belo
2 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to load data from JSON into a Bootstrap Table?
This article describes how a Bootstrap Table is created using a given JSON data. The data can be retrieved by either importing it or representing it in JavaScript. The following are given two methods to do it. Displaying JSON data without importing any file: The JSON file that has to be read can be represented using JavaScript. This can then be giv
4 min read
How to parse JSON Data into React Table Component ?
In React parsing JSON Data into React Table Component is a common task to represent data by building UI components. Prerequisites:NPM & Node JSReact JSJSON parse()Approach:We will create react table components and parse a JSON file consisting of objects with id, name, and city associated uniquely. We will use the .map() function to parse each o
2 min read
How to display static JSON data in table in Angular ?
In this article, we will see How to display static JSON data in the table in Angular. We will be displaying static data objects in Angular Table. We need to iterate over the object keys and values using key values and then handle them in the table. We will be using the bootstrap table and Angular PrimeNG Table template Steps for Installing & Co
3 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to Convert XML data into JSON using PHP ?
In this article, we are going to see how to convert XML data into JSON format using PHP. Requirements: XAMPP Server Introduction: PHP stands for hypertext preprocessor, which is used to create dynamic web pages. It also parses the XML and JSON data. XML stands for an extensible markup language in which we can define our own data. Structure of XML:
3 min read
Convert xml data into json using Node.js
XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human langua
2 min read
How to Convert HTML Form Field Values to JSON Object using JavaScript?
Storing HTML input data into JSON format using JavaScript can be useful in various web development scenarios such as form submissions, data processing, and AJAX requests. Here we will explore how to convert the HTML form input data into the JSON format using JavaScript. ApproachThe HTML file contains a form with input fields for name, email, and me
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
How to Convert Models Data into JSON in Django ?
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models Data Into Json Data In Django ? First create new
2 min read
How to Convert Blob Data to JSON in JavaScript ?
When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use the readAsText() method to read the Blob as text an
2 min read
How to Convert HTML to JSON in JavaScript ?
Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json LibraryUsing DOM ParserUsing html-to-json LibraryIn t
2 min read
HTML Code to JSON Converter App Using HTML, CSS, and JavaScript
HTML tables are a common way to represent structured data on web pages, but transforming this data into a JSON format can be troublesome. JSON is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate. We will be creating the HTML Code for the JSON Converter tool. The converter is desi
3 min read
How to create Table with 100% width, with Vertical Scroll inside Table body in HTML?
To add a vertical scroll bar inside the table body, use the overflow-y property. By changing the display property of tbody to block, we can display the block-level element. However, when changing the display property of tbody, we must also change the property of thead to prevent the table layout from breaking. ApproachApply the class scroll down to
2 min read
Convert CSV to HTML Table using Python Pandas and Flask Framework
In this article, we are going to convert a CSV file into an HTML table using Python Pandas and Flask Framework. Sample CSV file : USERNAME,IDENTIFIER,FIRST_NAME,LAST_NAME booker12,9012,Rachel,Booker grey07,2070,Laura,Grey johnson81,4081,Craig,Johnson jenkins46,9346,Mary,Jenkins smith79,5079,Jamie,SmithStepwise ImplementationCreating Environment Ste
2 min read
How to Convert HTML Table into Excel Spreadsheet using jQuery ?
In this article, we will learn how we can convert an HTML table into an Excel spreadsheet using jQuery. There are two ways available in jQuery to accomplish this task as discussed below: Table of Content Using the jQuery table2excel pluginBy creating the file download link in excel formatApproach 1: Using the jQuery table2excel pluginA simple jQuer
3 min read
Use of data files (CSV, JSON) in Postman for data-driven testing
It is a software testing method having all test input data stored or documented in a single CSV/JSON file and using a single test script for testing the API request with various input scenarios. It separates the test script logic from the test data. In Postman, we can perform this using variables and data files (CSV or JSON). Key Features of Data-D
2 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two me
3 min read
Convert Java Object to Json String using GSON
JSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To convert a Java object into JSON, the following methods can be
2 min read
Convert Json String to Java Object Using GSON
Pre-requisite: Convert Java Object to Json String Using GSONJSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To co
3 min read
How to convert JSON results into a date using JavaScript ?
The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are two methods which are discussed below: Approach 1: Use substr() method to get the integer part of the string.Use the parseInt() method followed by Date() to get the JavaScript date. Example: This example implements the above approach. C/C++ Code <h1 st
2 min read