Sunday 22 February 2015

jQuery Convert JSON Data to HTML Table using jQuery Row Append Properties

In this article ,I am explain how to convert JSON data to table form using jQuery. Many of time we got data in JSON form by using many APIs,Web Services, Web Methods etc. So here I try to solve that.

Designer Source Code :

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>convert json data to html table using jquery</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(function () {
            var myList = [{ "Name": "Jitendra Gangwar", "Designation": "Software Developer", "Location": "Delhi" },
                          { "Name": "Suraj", "Designation": "Software Developer", "Location": "Delhi" },
                          { "Name": "Arun", "Designation": "Software Developer", "Location": "Lucknow" },
                          { "Name": "Gaytri Mishra", "Designation": "HR", "Location": "Delhi" },
                          { "Name": "Dhirendra", "Designation": "Designer", "Location": "Lucknow" },
                          { "Name": "Sateesh", "Designation": "Software Developer", "Location": "Ghaziabad" },
                          { "Name": "Praveen", "Designation": "Manager", "Location": "Delhi"}]
            Bindhtmltable(myList);
        })
        function Bindhtmltable(list) {
            var cols = addheadercols(list);
            for (var i = 0; i < list.length; i++) {
                var row = $('<tr/>');
                for (var colIndex = 0; colIndex < cols.length; colIndex++) {
                    var cellValue = list[i][cols[colIndex]];
                    if (cellValue == null) { cellValue = ""; }
                    row.append($('<td/>').html(cellValue));
                }
                $("#htmltable").append(row);
            }
        }

        function addheadercols(list) {
            var colset = [];
            var headerTr = $('<tr/>');
            for (var i = 0; i < list.length; i++) {
                var rows = list[i];
                for (var key in rows) {
                    if ($.inArray(key, colset) == -1) {
                        colset.push(key);
                        headerTr.append($('<th/>').html(key));
                    }
                }
            }
            $("#htmltable").append(headerTr);
            return colset;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table id="htmltable" border="2" cellpadding="5">
        </table>
    </div>
    </form>
</body>
</html>

OutPut:



No comments:

Post a Comment