Wednesday, December 1, 2010

JSON to HTML table

There was a need to converting JSON object to HTML Table. I found out different solutions over internet. But there was no generic solution where I can pass a JSON string and get the HTML table in return. So, I tried out a solution with JavaScript. The code is as follows-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<title>Untitled Page</title>
<form id="form1" runat="form1">
<div id="test">
<script type="text/javascript">
var table = "[{'Country':'mycity','Name':'abc','Age':'29','Email':''}," +
"{'Name':'abcd','Age':'39','Email':''}," +
"{'Name':'abcde','Age':'30','Email':''}," +
table = eval('' + table + '');
var tableObject = function (json) {
var headerCount = new Object();
var createTR = function (id) {
var tr = document.createElement("tr");
tr.ID = id;
return tr;
var createTH = function (html) {
var th = document.createElement("th");
th.innerHTML = html;
return th;
var createTD = function (html) {
var td = document.createElement("td");
td.innerHTML = html;
return td;
var getName = function (id) {
for (var name in headerCount) {
if (eval("headerCount." + name) == id) {
return name;
var pTable;
if (json.length > 0) {
var index = 0;
pTable = document.createElement("table");
var head = createTR();
for (var i = 0; i < json.length; i++)
for (var item in json[i]) {
if (!headerCount.hasOwnProperty(item)) {
eval('headerCount.' + item + "=" + index);
for (var i = 0; i < json.length; i++) {
var row = new createTR(i);
for (var j = 0; j < index; j++) {
var name = getName(j);
if (eval("json[" + i + "].hasOwnProperty('" + name + "')")) {
row.appendChild(createTD(eval('json[' + i + '].' + name)));
return pTable;

var c = new tableObject(table);


  1. I have no words for this great post such a awe-some information i got gathered. Thanks to Author.
    html5 player| html5 video player

  2. thanx a lot that post weas really more thing is that i have a output in json but it not formatted,so i directly can't put it in the code i have to make few changes,so can you tell me how to do that

  3. It is not accepting if column name has a space

  4. How can i use this when the JSON object is coming from an AJAX request to a outside page?

    1. Simple. You can replace variable "table" with your ajax returned object. And place the whole code inside the success method of the ajax call.

  5. Hi Anup,

    Just wondering if its possible to convert facebook graph api output (Json format) to be converted to an html table. Can you please demonstrate an example please. Thank you.

    - James

    1. The json object need to be an array of JavaScript object. That's the any criteria.

  6. Hie Anup,

    I have a nested Json and want to display it as drill down HTML table. So what is the code for that?

  7. Hi,
    You can use the concept and repeat the same for nested tables.