3(H) : Read JSON Data and draw Data Table

 

 Data Visualization 

( 3160717 )

Practical and Source Codes



<!DOCTYPE html>
<html lang="en-IN" dir="ltr">

<head>
    <title>Read JSON File to Data Table</title>
    <meta charset="utf-8">
    <meta name="author" content="SidPro" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <meta name="description" content="Data visualization using javaScript and HTML" />
    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/jquery.csv.js"></script>
    <style>
        #mytable {
            font-family: Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        #mytable td,
        #mytable th {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #mytable tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        #mytable tr:hover {
            background-color: #ddd;
        }

        #mytable th {
            padding-top: 12px;
            padding-bottom: 12px;
            text-align: left;
            background-color: cornflowerblue;
            color: white;
        }
    </style>
</head>

<body>
    <h1>Get data from JSON file</h1>
    <table id="mytable">
    </table>
</body>
<script>
    var content = "";
    $(document).ready(function () {
        $.ajax({
            type: "Get",
            url: "data/regional_sales.json",
            dataType: "json",
            success: function (data) {
                var theData = data.sales.region;
                var theHead = Object.keys(theData[0]);

                content += "<tr>";
                theHead.forEach(TH);
                content += "</tr>";

                theData.forEach(function (v) {
                    v = Object.values(v);
                    content += "<tr>";
                    v.forEach(TD);
                    content += "</tr>";
                });

                $('#mytable').html(content);
            },
            error: function () {
                alert("json not found");
            }
        });
    });

    function TH(value) {
        content += "<th>" + value.toUpperCase() + "</th>";
    }
    function TD(value) {
        content += "<td>" + value + "</td>";
    }
</script>

</html>




Go Back

No comments:

Get new posts by email:


APY Logo