How to convert json data into html table?

by darrion.kuhn , in category: HTML & CSS , 9 months ago

How to convert json data into html table?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 9 months ago

@darrion.kuhn 

You can convert JSON data into an HTML table using JavaScript. Here is an example code snippet that demonstrates how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html>
<head>
    <title>JSON to HTML Table</title>
</head>
<body>

<div id="table-container"></div>

<script>
    // Example JSON data
    var jsonData = [
        { name: "John", age: 30, city: "New York" },
        { name: "Alice", age: 25, city: "San Francisco" },
        { name: "Bob", age: 35, city: "Los Angeles" }
    ];

    // Create a function to convert JSON data into an HTML table
    function jsonToHtmlTable(data) {
        var table = '<table border="1">';
        
        // Create table headers
        table += '<tr>';
        for (var key in data[0]) {
            if (data[0].hasOwnProperty(key)) {
                table += '<th>' + key + '</th>';
            }
        }
        table += '</tr>';

        // Fill in table rows with data
        data.forEach(function(item) {
            table += '<tr>';
            for (var key in item) {
                if (item.hasOwnProperty(key)) {
                    table += '<td>' + item[key] + '</td>';
                }
            }
            table += '</tr>';
        });

        table += '</table>';
        return table;
    }

    // Display the HTML table on the webpage
    document.getElementById('table-container').innerHTML = jsonToHtmlTable(jsonData);
</script>

</body>
</html>


This code snippet creates an HTML table from the JSON data provided in the jsonData variable. It dynamically generates table headers and fills in the rows with the JSON data. Finally, it displays the HTML table in the table-container div on the webpage.