8

I need to create HTML table based on JSON input. here is my JSON sample input.

[
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "sac@gmail.com"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "Binu@gmail.com"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "cal@gmail.com"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "nera@gmail.com"
  }
]

Expected result:

enter image description here

I need to do this while the web page is loading.

Lix
  • 47,311
  • 12
  • 103
  • 131
Rooter
  • 383
  • 1
  • 7
  • 25
  • Is there any specific thing you need assistance with? Can you please share with us any attempts you have made? It'll be a lot easier to help if we see which direction you have chosen to take. – Lix Mar 02 '17 at 14:30
  • 1
    So loop over and build a table. Do you know how to loop over the array? Do you know how to build a string? – epascarello Mar 02 '17 at 14:31
  • I think if you dont know secific keys you have to do this using recursion – Maciej Kozieja Mar 02 '17 at 14:32
  • @MaciejKozieja - no need for recursion here. `Object.keys()` will get you all of the keys for an object - you can then iterate over them just like a normal array. – Lix Mar 02 '17 at 14:33
  • @epascarello no i don't know friend :( can you provide me some sample code to do this – Rooter Mar 02 '17 at 14:35
  • @Lix how can i do this,can you help me to? i am new to this :( – Rooter Mar 02 '17 at 14:36
  • @Rooter - if you don't know how to loop over an array or build a string I think you might have some additional work to do before attempting to solve this problem. We're talking about some of the first thing one learns when starting to program. – Lix Mar 02 '17 at 14:36
  • @lix if you have obejct inside obejct inside object this loop would be over complicated – Maciej Kozieja Mar 02 '17 at 14:36
  • @MaciejKozieja - no one mentioned nested objects :) I am taking the OPs sample JSON as the example (since it is the only one given) – Lix Mar 02 '17 at 14:37
  • It is JavaScript basics: http://stackoverflow.com/questions/18238173/javascript-loop-through-json-array learn the basics – epascarello Mar 02 '17 at 14:37

4 Answers4

9

Go through all elements from your JSON array and save all different keys to javascript array or similar.

Then, using all these keys create table and table header row with columns.

Then, go through all JSON objects and print one row for each object.

var data = [
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "sac@gmail.com"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "Binu@gmail.com"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "cal@gmail.com"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "nera@gmail.com"
  }
];

var keys = [];

document.write("<table border==\"1\"><tr>");
for (key in data[0]) {
 document.write('<td>' + key + '</td>');
}
document.write("</tr>");
for (var i = 0; i < data.length; i++) {
 document.write('<tr>');
 for (key in data[i]) {
   document.write('<td>' + data[i][key] + '</td>');
  }
 document.write('</tr>');
}
document.write("</table>");
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
8

I have done your job, as you don't know. Please follow my code below and do changes what you needed in your application. But you should include library files hosted by your server for faster results::

FULL CODE

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
    var data = [
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "sac@gmail.com"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "Binu@gmail.com"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "cal@gmail.com"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "nera@gmail.com"
  }
];
$(document).ready(function () {
    var html = '<table class="table table-striped">';
    html += '<tr>';
    var flag = 0;
    $.each(data[0], function(index, value){
        html += '<th>'+index+'</th>';
    });
    html += '</tr>';
     $.each(data, function(index, value){
         html += '<tr>';
        $.each(value, function(index2, value2){
            html += '<td>'+value2+'</td>';
        });
        html += '<tr>';
     });
     html += '</table>';
     $('body').html(html);
});
</script>

AND it will look like image below:

enter image description here

Rana Ghosh
  • 4,514
  • 5
  • 23
  • 40
  • 1
    You've hard coded the columns of the table. The question was to build a table according to the provided JSON object. Any change to that object will break your code. – Lix Mar 02 '17 at 14:47
  • 1
    In addition you have forgotten to mention a dependency you have used. `table-striped` is from `bootstrap` if I'm not mistaken.. – Lix Mar 02 '17 at 14:47
  • Yes i am sending please wait. – Rana Ghosh Mar 02 '17 at 14:56
  • @Rooter Please follow my updated answer – Rana Ghosh Mar 02 '17 at 15:02
  • @Lix Ahh, sorry i was in a hurry. Now i think negative is required. – Rana Ghosh Mar 02 '17 at 15:03
  • @rooter if it worked for you please accept the answer for helping others – Rana Ghosh Mar 02 '17 at 15:38
  • What mail. I just answeresd your question – Rana Ghosh Mar 02 '17 at 15:42
  • @RanaGhosh ok dude,sorry logged with my mobile,so i didn't saw answer properly , thanks , i'll check and accept it – Rooter Mar 02 '17 at 15:47
  • @RanaGhosh hey friend, suppose JSON is generate by php, so then how to give a json input as a parameter to this function – Sachith Wickramaarachchi Mar 02 '17 at 16:00
  • @RanaGhosh your code working fine ,but i have some two problem. problem 1: when i use this in php,when i executed your code with some other things,only this table showing and not other content displaying(ex: images), problem 2: how i can send json as parameter to this function – Rooter Mar 02 '17 at 17:50
2

This is what I would have done

var object = [
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "sac@gmail.com"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "Binu@gmail.com"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "cal@gmail.com"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "nera@gmail.com"
  }
];


function createTable(){
 $('#content').append('<table id="jsonTable"><thead><tr></tr></thead><tbody></tbody></table>');
 
  $.each(Object.keys(object[0]), function(index, key){
    $('#jsonTable thead tr').append('<th>' + key + '</th>');
  }); 
  $.each(object, function(index, jsonObject){     
    if(Object.keys(jsonObject).length > 0){
      var tableRow = '<tr>';
      $.each(Object.keys(jsonObject), function(i, key){
         tableRow += '<td>' + jsonObject[key] + '</td>';
      });
      tableRow += "</tr>";
      $('#jsonTable tbody').append(tableRow);
    }
 });
}

$(document).ready(function(){
  createTable();
});
tr:nth-child(even) td {background: #f2f2f2}

table{
 border-collapse: collapse;
}
table td, table th{
 border: 1px solid black;
  text-align: left;
}
table thead{
 background:#ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="content"></div>
Brent Boden
  • 569
  • 2
  • 10
  • You are creating the table header dynamically according to the provided JSON, but then when populating the table you are still using hard coded keys - this code will break if the JSON changes at all (adding an extra key) – Lix Mar 02 '17 at 14:52
  • 1
    @Lix I just modified my code so it would work if you added a new key – Brent Boden Mar 02 '17 at 14:54
-2
var data = jsonObject;
var table = document.createElement("table");
var tr = document.createElement("tr");
var thUserID = document.createElement("th");
var thUserName = document.createElement("th");
var thPassword = document.createElement("th");
var thCountry = document.createElement("th");
var thEmail = document.createElement("th");
thUserID.innerText = "userID";
thUserName.innerText = "userName";
thPassword.innerText = "password";
thCountry.innerText = "country";
thEmail.innerText = "email";
tr.appendChild(thUserID);
tr.appendChild(thUserName);
tr.appendChild(thPassword);
tr.appendChild(thCountry);
tr.appendChild(thEmail);    
for(var i=0; i<data.length; i++) {
    var userID = data[i].UserID;
    var userName = data[i].UserName;
    var password = data[i].Password;
    var country = data[i].Country;
    var email = data[i].Email;
    var tr = document.createElement("tr");
    var tdUserID = document.createElement("td");
    tdUserID.innerText = userID;
    var tdUserName = document.createElement("td");
    tdUserName.innerText = userName;
    var tdPassword = document.createElement("td");
    tdPassword.innerText = password;
    var tdCountry = document.createElement("td");
    tdCountry.innerText = country;
    var tdEmail = document.createElement("td");
    tdEmail.innerText = email;
    tr.appendChild(tdUserID);
    tr.appendChild(tdUserName);
    tr.appendChild(tdPassword);
    tr.appendChild(tdCountry);
    tr.appendChild(tdEmail);
    table.appendChild(tr);
}
document.body.appendChild(table);
user1529413
  • 458
  • 8
  • 19
  • I see that you are just trying to help out - but this solution is too hard coded - the moment the JSON data changes (adding an extra key), this code will break. – Lix Mar 02 '17 at 14:45
  • The more I use StackOverflow the less I like it. You asked a specific question you got a specific answer. You could use a for(i in data) instead if you'd like. – user1529413 Mar 02 '17 at 17:53
  • 1
    Wow, I got a down vote for answering the question exactly but it failed to anticipate that the OP may have wanted something different? – user1529413 Mar 03 '17 at 02:05