0

Instead of printing out the employees info in a line, I would like to use the variable "obj" to create a html table wif all the employees info. However, I am unable to pass in "obj". Please advise.

var text = '{"employees":[' + '{"Name":"Tony","Mobile":"99221111","Email":"tony@json.com" },' + '{"Name":"Linda","Mobile":"98981111","Email":"linda@json.com" },' + '{"Name":"Patrick","Email":"patrick@json.com" },' + '{"Name":"Isabella","Mobile":"99552222" }]}'; 
obj = JSON.parse(text);

function buildHtmlTable(selector) {
  var columns = addAllColumnHeaders(obj, selector);

  for (var i = 0; i < obj.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = obj[i][columns[colIndex]];
      if (cellValue == null) cellValue = "";
      row$.append($('<td/>').html(cellValue));
    }
    $(selector).append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(obj, selector) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < obj.length; i++) {
    var rowHash = obj[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $(selector).append(headerTr$);
<!DOCTYPE html>
<html>
<head>
 <title>Task 1</title>
</head>
<body onLoad="buildHtmlTable('#excelDataTable')">
  <table id="excelDataTable" border="1">
  </table>
 <p id="demo"></p>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script src = "Task1ab.js"></script>
</body>
</html>
Janice
  • 13
  • 3
  • You can look into this http://json2html.com/ – Abdul Basit Feb 12 '19 at 08:05
  • Possible duplicate of [Convert json data to a html table](https://stackoverflow.com/questions/5180382/convert-json-data-to-a-html-table) – Charlie Feb 12 '19 at 08:14
  • Please go through the JSFiddle, https://jsfiddle.net/v7kzgskf/4/ There is also Datatables - which could add more feature like search,sort to your table – mightyteja Feb 12 '19 at 08:29

3 Answers3

0

Kindly follow this link : https://www.encodedna.com/javascript/populate-json-data-to-html-table-using-javascript.htm

<!DOCTYPE html>
    <html>
    <head>
        <title>Example</title>
        <style>
            th, td, p, input {
                font:14px;
            }
            table, th, td 
            {
                border: solid 1px #DDD;
                border-collapse: collapse;
            }
            th {
                font-weight:bold;
            }
        </style>
    </head>
    <body>
        <input type="button" onclick="CreateTable()" value="Create Table From JSON" />
        <p id="showData"></p>
    </body>

    <script>
        function CreateTable() {
            var employees = [
        {
          "Name": "Tony",
          "Mobile": "99221111",
          "Email": "tony@json.com"
        },
        {
          "Name": "Linda",
          "Mobile": "98981111",
          "Email": "linda@json.com"
        },
        {
          "Name": "Patrick",
          "Email": "patrick@json.com"
        },
        {
          "Name": "Isabella",
          "Mobile": "99552222"
        }
      ]

            // EXTRACT VALUE FOR HTML HEADER. 
            var col = [];
            for (var i = 0; i < employees.length; i++) {
                for (var key in employees[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE DYNAMIC TABLE.
            var table = document.createElement("table");

            // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

            var tr = table.insertRow(-1);                   // TABLE ROW.

            for (var i = 0; i < col.length; i++) {
                var th = document.createElement("th");      // TABLE HEADER.
                th.innerHTML = col[i];
                tr.appendChild(th);
            }

            // ADD JSON DATA TO THE TABLE AS ROWS.
            for (var i = 0; i < employees.length; i++) {

                tr = table.insertRow(-1);

                for (var j = 0; j < col.length; j++) {
                    var tabCell = tr.insertCell(-1);
                    tabCell.innerHTML = employees[i][col[j]] ? employees[i][col[j]] : 'NA';
                }
            }

            // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
            var divContainer = document.getElementById("showData");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);
        }
    </script>
    </html>
Anchal Singh
  • 364
  • 4
  • 10
0

It is very straightforward to wrap your json fields with .

There are enough libraries which does that too.

You can use the jput jquery plugin or json2html as well.

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${age}"}
        ]}
    ]}
]};

var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];

See this answer

$('#target_div').html(json2html.transform(data,transform));
Charlie
  • 22,886
  • 11
  • 59
  • 90
0

Change 1 : you are referring to obj as the Array . But the actual array is employees inside the object.. so obj = JSON.parse(text).employees; is what we need to iterate through

Change 2 :var columns = addAllColumnHeaders(obj, selector); is expecting a return value. But the function addAllColumnHeaders returns nothing. so add return statement return columnSet; in the function.

Modified js code is as below

var text = '{"employees":[' + '{"Name":"Tony","Mobile":"99221111","Email":"tony@json.com" },' + '{"Name":"Linda","Mobile":"98981111","Email":"linda@json.com" },' + '{"Name":"Patrick","Email":"patrick@json.com" },' + '{"Name":"Isabella","Mobile":"99552222" }]}'; 
obj = JSON.parse(text).employees;

function buildHtmlTable(selector) {
  var columns = addAllColumnHeaders(obj, selector);

  for (var i = 0; i < obj.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = obj[i][columns[colIndex]];
      if (cellValue == null) cellValue = "";
      row$.append($('<td/>').html(cellValue));
    }
    $(selector).append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(obj, selector) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < obj.length; i++) {
    var rowHash = obj[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $(selector).append(headerTr$);
  return columnSet;

  }

Hope this helps. Thanks

Jai
  • 91
  • 3