如何使用 JavaScript/jQuery 將 JSON 資料轉換為 HTML 表格?


JSON(JavaScript 物件表示法)是一種強大的資料格式,用於在伺服器和客戶端之間交換資料,反之亦然。HTML 表格 是以表格格式表示資料的強大工具,因此非常易於閱讀、分析和比較。在 Web 開發中,將 JSON 資料轉換為 HTML 表格非常常見。

在本文中,我們將學習如何使用Javascript 以及jQuery 將 JSON 資料轉換為 HTML 表格。在本文結束時,您將對 JSON 到 HTML 表格的轉換有一個紮實的瞭解。

使用 JavaScript 將 JSON 資料轉換為 HTML 表格

以下是使用 JSON 資料建立 HTML 表格的步驟。

  • 建立一個名為“convert”的函式。

  • 建立一個示例 JSON 資料。

  • 使用 getElementByID(“container”) 獲取容器,我們將在其中追加表格。

  • 獲取 JSON 資料第一個物件的鍵,以便獲取表格的標題。

  • 迴圈遍歷列名,建立表頭單元格,並將列名設定為表頭單元格的文字。

  • 將表頭單元格追加到表頭行,然後將表頭行追加到表頭。

  • 將表頭追加到表格。

  • 迴圈遍歷 JSON 資料,建立表格行,使用 Object.values(item) 獲取 JSON 資料中當前物件的 value,並建立表格單元格。

  • 將 value 設定為表格單元格的文字,將表格單元格追加到表格行,然後將表格行追加到表格。

示例

在此示例中,我們使用 Javascript 將 JSON 資料轉換為 HTML 表格。

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

示例:使用 jQuery 將 JSON 資料轉換為 HTML 表格

以下是使用 jQuery 將 JSON 資料轉換為 HTML 表格的程式碼。

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

更新於: 2023年10月31日

58K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.