Table of Contents
Convert JSON data to HTML table using JavaScript
Example
Example: Convert JSON data to HTML table using jQuery
Home Web Front-end JS Tutorial How to convert JSON data to html table using JavaScript/jQuery?

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

Sep 10, 2023 am 08:13 AM

如何使用 JavaScript/jQuery 将 JSON 数据转换为 html 表?

JSON (JavaScript Object Notation) is a powerful data format used for exchanging data between servers and clients. HTML tables are powerful tools for representing data in a tabular format, making it very easy to read, analyze, and compare. In web development, it's common to convert JSON data into HTML tables.

In this article, we will learn how to convert JSON data into an HTML table using Javascript and jQuery. After reading this article, you will have a solid understanding of JSON to HTML table conversion.

Convert JSON data to HTML table using JavaScript

The following are the steps to create an HTML table using JSON data.

  • Create a function named "convert".

  • Create sample JSON data.

  • Use getElementByID("container") to get the container into which we will append the table.

  • Get the key of the first object of the JSON data so we can get the title of the table.

  • Loop through the column names, create a header cell, and set the column name to the text of the header cell.

  • Append header cells to header rows and then append header rows to headers

  • Append title to table

  • Loop through JSON data, create table rows, use Object.values(item) to get the value of the current object in the JSON data, and create table cells.

  • Set the value to the text of the table cell, append the table cell to the table row, and then append the table row to the table.

Example

In this example, we use Javascript to convert JSON data into an HTML table.

<html>
<head>
   <style>
      table, th, td {
         border: 1px solid black;
         border-collapse: collapse; 
      }
      td, th {
         padding: 10px;
      }
   </style>
</head>
<body>
   <h2>Convert JSON data into a html table using Javascript</h2>
   <p>Click the following button to convert JSON results into HTML table</p><br>
   <button id="btn" onclick="convert( )"> Click Here </button> <br>
   <h3> Resulting Table: </h3>
   <div id="container"></div>
   <script>
   
      // Function to convert JSON data to HTML table
      function convert() {
         
         // Sample JSON data
         let jsonData = [
            {
               name: "Saurabh",
               age: "20",
               city: "Prayagraj"
            },
            {
               name: "Vipin",
               age: 23,
               city: "Lucknow",
            },
            {
               name: "Saksham",
               age: 21,
               city: "Noida"
            }
         ];
         
         // Get the container element where the table will be inserted
         let container = document.getElementById("container");
         
         // Create the table element
         let table = document.createElement("table");
         
         // Get the keys (column names) of the first object in the JSON data
         let cols = Object.keys(jsonData[0]);
         
         // Create the header element
         let thead = document.createElement("thead");
         let tr = document.createElement("tr");
         
         // Loop through the column names and create header cells
         cols.forEach((item) => {
            let th = document.createElement("th");
            th.innerText = item; // Set the column name as the text of the header cell
            tr.appendChild(th); // Append the header cell to the header row
         });
         thead.appendChild(tr); // Append the header row to the header
         table.append(tr) // Append the header to the table
         
         // Loop through the JSON data and create table rows
         jsonData.forEach((item) => {
            let tr = document.createElement("tr");
            
            // Get the values of the current object in the JSON data
            let vals = Object.values(item);
            
            // Loop through the values and create table cells
            vals.forEach((elem) => {
               let td = document.createElement("td");
               td.innerText = elem; // Set the value as the text of the table cell
               tr.appendChild(td); // Append the table cell to the table row
            });
            table.appendChild(tr); // Append the table row to the table
         });
         container.appendChild(table) // Append the table to the container element
      }
   </script>
</body>
</html>
Copy after login

Example: Convert JSON data to HTML table using jQuery

Here is the code to convert JSON data into an HTML table using jQuery.

<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
   <style>
      table, th, td { border: 1px solid black; border-collapse: collapse; }
      td, th {padding: 10px;}
   </style>
</head>
<body>
   <h2>Convert JSON data into a html table using Jquery</h2>
   <p>Click the following button to convert JSON results into HTML table</p> <br>
   <button id="btn" onclick="convert( )"> Click Here </button> <br>
   <h3> Resulting Table: </h3> 
   <div id="container"></div>
   <script>
      
      // Function to convert JSON data to HTML table
      function convert() {
         
         // Sample JSON data
         let jsonData = [
            {
               name: "Saurabh",
               age: "20",
               city: "Prayagraj"
            },
            {
               name: "Vipin",
               age: 23,
               city: "Lucknow",
            },
            {
               name: "Saksham",
               age: 21,
               city: "Noida"
            }
         ];
         
         // Get the container element where the table will be inserted
         let container = $("#container");
         
         // Create the table element
         let table = $("<table>");
         
         // Get the keys (column names) of the first object in the JSON data
         let cols = Object.keys(jsonData[0]);
         
         // Create the header element
         let thead = $("<thead>");
         let tr = $("<tr>");
         
         // Loop through the column names and create header cells
         $.each(cols, function(i, item){
            let th = $("<th>");
            th.text(item); // Set the column name as the text of the header cell
            tr.append(th); // Append the header cell to the header row
         });
         thead.append(tr); // Append the header row to the header
         table.append(tr) // Append the header to the table
         
         // Loop through the JSON data and create table rows
         $.each(jsonData, function(i, item){
         let tr = $("<tr>");
            
            // Get the values of the current object in the JSON data
            let vals = Object.values(item);
            
            // Loop through the values and create table cells
            $.each(vals, (i, elem) => {
               let td = $("<td>");
               td.text(elem); // Set the value as the text of the table cell
               tr.append(td); // Append the table cell to the table row
            });
            table.append(tr); // Append the table row to the table
         });
         container.append(table) // Append the table to the container element
      }
   </script> 
 </body>
</html>
Copy after login

The above is the detailed content of How to convert JSON data to html table using JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles