如何在 JavaScript 中將 HTML 表格轉換為 JSON?


使用 Web 應用程式通常需要解析一些 HTML 表格以提取內容的適當格式,最常見的是 JSON 格式,該格式更適合儲存、傳輸或 API 通訊。JSON 是最流行的資料交換格式之一,主要是因為它輕量級且易於在前端和後端整合。本文重點介紹了在 JavaScript 中建立 HTML 表格的 JSON 表示的不同方法。

將 HTML 表格轉換為 JSON 的方法

使用 querySelector 和迴圈

透過這種方式,我們從表格的行和單元格中提取資料,並建立必要的 JSON 物件。這是處理任何結構表格最靈活的方法。

示例程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
        <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>HTML Table to JSON</title>
</head>
<body>
    <table id="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Pankaj</td>
                <td>20</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Neeraj</td>
                <td>18</td>
            </tr>
        </tbody>
    </table>

    <script>
        function tableToJson() {
            const table = document.getElementById('data-table');
            const headers = Array.from(table.querySelectorAll('thead th')).map(th => th.textContent);
            const rows = Array.from(table.querySelectorAll('tbody tr'));
            const json = rows.map(row => {
                const cells = Array.from(row.querySelectorAll('td'));
                let obj = {};
                headers.forEach((header, i) => {
                    obj[header] = cells[i].textContent;
                });
                return obj;
            });
            return json;
        }
        document.write("<br>")
        document.write(JSON.stringify(tableToJson(), null, 2));
    </script>
</body>
</html>

輸出

ID	Name	Age
1	Pankaj	20
2	Neeraj	18

[ { "ID": "1", "Name": "Pankaj", "Age": "20" }, 
  { "ID": "2", "Name": "Neeraj", "Age": "18" } ]

使用 Array.from 和 forEach

此方法首先結合使用陣列,它更優雅地處理行和單元格,並且更好地處理可讀性。邏輯相同,但使用forEach方法代替手動迴圈。

示例程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
        <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>HTML Table to JSON</title>
</head>
<body>
    <table id="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Pankaj</td>
                <td>20</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Neeraj</td>
                <td>18</td>
            </tr>
        </tbody>
    </table>

    <script>
        function tableToJson() {
            const headers = Array.from(document.querySelectorAll('#data-table thead th')).map(th => th.textContent);
            const json = [];
            document.querySelectorAll('#data-table tbody tr').forEach(row => {
                const rowData = {};
                Array.from(row.children).forEach((cell, i) => {
                    rowData[headers[i]] = cell.textContent;
                });
                json.push(rowData);
            });
            return json;
        }
        document.write("<br>")
        document.write(JSON.stringify(tableToJson(), null, 2));
    </script>
</body>
</html>

輸出

ID	Name	Age
1	Pankaj	20
2	Neeraj	18

[ { "ID": "1", "Name": "Pankaj", "Age": "20" }, 
  { "ID": "2", "Name": "Neeraj", "Age": "18" } ]

使用 jQuery 簡化遍歷

如果您已經在使用 jQuery,那麼您可以使用 jQuery 的方法(例如 each()text())簡化 DOM 選擇和遍歷。

示例程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>HTML Table to JSON</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
    </script>
</head>
<body>
    <table id="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Pankaj</td>
                <td>20</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Neeraj</td>
                <td>18</td>
            </tr>
        </tbody>
    </table>

    <script>
        function tableToJson() {
            const headers = [];
            $('#data-table thead th').each(function() {
                headers.push($(this).text());
            });

            const json = [];
            $('#data-table tbody tr').each(function() {
                const rowData = {};
                $(this).find('td').each(function(index) {
                    rowData[headers[index]] = $(this).text();
                });
                json.push(rowData);
            });
            return json;
        }
        document.write("<br>")
        document.write(JSON.stringify(tableToJson(), null, 2));
    </script>
</body>
</html>

輸出

ID	Name	Age
1	Pankaj	20
2	Neeraj	18

[ { "ID": "1", "Name": "Pankaj", "Age": "20" }, 
  { "ID": "2", "Name": "Neeraj", "Age": "18" } ]

更新於:2024年11月14日

瀏覽量:10

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告