简体   繁体   中英

Populating html table with JSON object data

I am taking a csv file from fileUpload control and have converted the csv file to JSON object also. Now I am trying to populate the html table with this JSON data. I have written a populatetable() function but its not showing data properly. The CSV to JSON conversion is happening properly as can be seen here - JSON object

HTML file:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
    <!--<script type="text/javascript" src="JavaScript.js"></script>-->
    <script type="text/javascript" src="CSV_to_JSON.js"></script>


    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }

        th, td {
            padding: 15px;
        }

        th {
            text-align: left;
        }

        table {
            border-spacing: 5px;
        }

        .guide {
            text-decoration: underline;
            text-align: center;
        }

        .odd {
            color: #fff;
            background: #666;
        }

        .even {
            color: #666;
        }

        .hot {
            border: 1px solid #f00;
        }
    </style>

</head>
<body>

    <div class="container">
        <div class="row">
            <h2>---</h2>
        </div>
        <div class="panel panel-primary">
            <div class="panel-heading">---</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-sm-12 col-sm-offset-1">

                        <form id="form1" runat="server" class="form-horizontal">
                            <div class="form-group">
                                <div class="col-sm-5">
                                    <div class="col-sm-6">
                                        <input type="file" accept=".csv" id="fileUpload" />
                                    </div>
                                    <div class="col-sm-6">
                                        <input type="button" id="upload" class="btn btn-primary" value="Upload" />
                                    </div>

                                </div>
                                <div class="col-sm-7">
                                    <div class="col-sm-2">
                                        <input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" />
                                    </div>
                                    <div class="col-sm-2">
                                        <input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" />
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-default" style="align-self: center">
                            <div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <center>
                                                        <div class="input-append" id="filterDev" style="visibility:hidden">
                                                          <input name="search" id="inputFilter" placeholder="Enter ID to filter" />
                                                             <input type="button" value="Filter" id="filter" class="btn btn-primary" />
                                                                </div></center>
                                    </div>
                                    <br />
                                    <br />

                                </div>
                                <div class="row">
                                    <div class="col-sm-12" id="dvCSV"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="col-sm-3">
                            <p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
                        </div>
                        <div class="col-sm-3">
                            <p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


</body>
</html>
<script type="text/javascript">

    $("#cancel").on("click", function () {
        $('input:checked').each(function () {
            $(this).closest("tr").remove();
        });
    });

    /*$('#inputFilter').keyup(function () {
        var that = this;
        $.each($('tr'),
        function (i, val) {
            if ($(val).text().indexOf($(that).val()) == -1) {
                $('#name').animate({
                    marginTop: 0
                },
                50,
                function () {
                    $('tr').eq(i).hide();
                });
            } else {
                $('#name').animate({
                    marginTop: 0
                },
                50,
                function () {
                    $('tr').eq(i).show();
                });
            }
        });
    });*/

    $(function () {
        $("#process").bind("click", function () {

            document.getElementById("File1").style.visibility = "visible";
            document.getElementById("File2").style.visibility = "visible";
            document.getElementById("download").style.visibility = "visible";

        });

    });

</script>

CSV_to_JSON.js -

$(function () {
    $("#upload").bind("click", function () {

        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
        if (regex.test($("#fileUpload").val().toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    //var table = $("<table id='name'/>");
                    var lines = e.target.result.split("\n");
                    var result = [];
                    var headers = lines[0].split(",");
                    //alert(headers);

                    for (var i = 1; i < lines.length; i++) {
                        var obj = {};
                        var currentline = lines[i].split(",");

                        for (var j = 0; j < headers.length; j++) {
                            obj[headers[j]] = currentline[j];
                        }
                        result.push(obj);
                    }
                    alert(JSON.stringify(result));
                    populateTable(JSON.stringify(result));
                }
                reader.readAsText($("#fileUpload")[0].files[0]);
            }
        }

    });
});

function populateTable(object) {

    var obj = object;
    var table = $("<table />");
    table[0].border = "1";
    var columnCount = obj[0].length;
    var row = $(table[0].insertRow(-1));

    for (var i = 0; i < columnCount; i++) {
        var headerCell = $("<th />");
        headerCell.html(obj[0][i]);
        row.append(headerCell);
    }

    for (var i = 1; i < obj.length; i++) {
        row = $(table[0].insertRow(-1));
        for (var j = 0; j < columnCount; j++) {
            var cell = $("<td />");
            cell.html(obj[i][j]);
            row.append(cell);
        }
    }

    var dvTable = $("#dvCSV");
    dvTable.html("");
    dvTable.append(table);

}

How can this data be displayed properly in a html table?

The issue stems from how you're getting the keys from the JSON object. An object doesn't have a length property and you can't iterate through its keys like an array directly without calling Object.keys() on one of the objects::

var columns = Object.keys(obj[0]);
// gives ["ID","Name","City","Address","Designation"]

From there you can get the column length and refer to the columns array to set up your header row:

var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
    var headerCell = $("<th />");
    headerCell.html([columns[i]]);
    row.append(headerCell);
}

You'll also need to modify your loop that sets up the subsequent table rows to look up the column name when creating each cell for each row:

for (var i = 0; i < obj.length; i++) {
    row = $(table[0].insertRow(-1));
    for (var j = 0; j < columnCount; j++) {
        var cell = $("<td />");
        cell.html(obj[i][columns[j]]);
        row.append(cell);
    }
}

Here's a demo with some mock data:

 var mockData = [{ "ID": 1, "Name": "Kevin", "City": "Santa Clara", "Address": "Longmen", "Designation": "VP Marketing" }, { "ID": 2, "Name": "Tina", "City": "São Bartolomeu", "Address": "Bojongloa", "Designation": "Computer Systems Analyst III" }, { "ID": 3, "Name": "Kevin", "City": "Cilolohan", "Address": "Tai'an", "Designation": "Paralegal" }, { "ID": 4, "Name": "Rebecca", "City": "Runović", "Address": "Tessaoua", "Designation": "Human Resources Manager" }, { "ID": 5, "Name": "Nancy", "City": "Merritt", "Address": "Yur'yevets", "Designation": "Assistant Manager" }, { "ID": 6, "Name": "Anne", "City": "Pio Duran", "Address": "Kuala Lumpur", "Designation": "Sales Representative" }, { "ID": 7, "Name": "Scott", "City": "Xiamao", "Address": "Banjarmasin", "Designation": "Computer Systems Analyst II" }, { "ID": 8, "Name": "Howard", "City": "Rzeczenica", "Address": "Nanyo", "Designation": "Recruiting Manager" }, { "ID": 9, "Name": "Frances", "City": "Tubuhue", "Address": "Rambatan", "Designation": "Senior Quality Engineer" }, { "ID": 10, "Name": "Bruce", "City": "Gandi", "Address": "Manuel Roxas", "Designation": "Senior Financial Analyst" }, { "ID": 11, "Name": "Victor", "City": "Liuhou", "Address": "Sambirejo", "Designation": "Actuary" }, { "ID": 12, "Name": "Phillip", "City": "Fubei", "Address": "Ulset", "Designation": "Account Representative II" }, { "ID": 13, "Name": "Cheryl", "City": "Chasŏng", "Address": "Otok", "Designation": "Mechanical Systems Engineer" }, { "ID": 14, "Name": "Arthur", "City": "Shimodate", "Address": "Morada Nova", "Designation": "Payment Adjustment Coordinator" }, { "ID": 15, "Name": "Jean", "City": "Mojo", "Address": "Pushkino", "Designation": "Budget/Accounting Analyst II" }, { "ID": 16, "Name": "Russell", "City": "Qīrah", "Address": "Vista Hermosa", "Designation": "Research Assistant III" }, { "ID": 17, "Name": "Larry", "City": "Garoua Boulaï", "Address": "Guanchi", "Designation": "Office Assistant I" }, { "ID": 18, "Name": "Kathleen", "City": "Thongwa", "Address": "Awilega", "Designation": "Social Worker" }, { "ID": 19, "Name": "Michael", "City": "Hongqi", "Address": "Karatau", "Designation": "Electrical Engineer" }, { "ID": 20, "Name": "Anna", "City": "Xiacang", "Address": "K Bang", "Designation": "Product Engineer" }]; function populateTable(object) { var obj = object; var table = $("<table />"); table[0].border = "1"; var columns = Object.keys(obj[0]); var columnCount = columns.length; var row = $(table[0].insertRow(-1)); for (var i = 0; i < columnCount; i++) { var headerCell = $("<th />"); headerCell.html([columns[i]]); row.append(headerCell); } for (var i = 0; i < obj.length; i++) { row = $(table[0].insertRow(-1)); for (var j = 0; j < columnCount; j++) { var cell = $("<td />"); cell.html(obj[i][columns[j]]); row.append(cell); } } var dvTable = $("#dvCSV"); dvTable.html(""); dvTable.append(table); } populateTable(mockData) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="dvCSV"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM