JSFiddle - React, Tailwind, and code Playground

by bvotcode

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Convert HTML Table to JSON (jQuery)</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <h1>GeeksForGeeks</h1>
    <h5>Approach 2: Using a Library (jQuery)</h5>
    <table id="data-table" border="1">
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
        </tr>
        <tr>
            <td>Pankaj Bind</td>
            <td>20</td>
            <td>India</td>
        </tr>
        <tr>
            <td>Sandeep Kumar</td>
            <td>20</td>
            <td>India</td>
        </tr>
    </table>

    <script>
        function tableToJson() {
            const jsonData = [];
            const headers = [];

            $("#data-table tr").each(function (index) {
                if (index === 0) {
                    $(this).find('th').each(function () {
                        headers.push($(this).text());
                    });
                } else {
                    const rowObject = {};
                    $(this).find('td').each(function (i) {
                        rowObject[headers[i]] = $(this).text();
                    });
                    jsonData.push(rowObject);
                }
            });

            return JSON.stringify(jsonData, null, 2);
        }

        console.log(tableToJson());
    </script>
</body>

</html>