So you’ve just called your first REST service and have JSON array full of data… Where do you put it? I noticed lots of people using various plug-ins to create HTML tables by defining columns, data types, etc… but what happens when you don’t know this? Since I wanted to throw random JSON data into HTML tables, I created two helper functions that will iterate over the data to create the views.
This code below is an improvement to my ad-hoc JavaScript solution I created a few weeks ago for a ASP.NET project, link below. As you will see below, it’s pretty easy to render a HTML table from a object array using plain JavaScript. Since most results are in a Table or Detail layout, I created 2 functions to return the data in either format. I also added some optional parameters that you can set to control formatting. The Details View was designed to show a single row/object, the headers will display on the left and the data will display on the right (see second example).
// This function creates a standard table with column/rows
// Parameter Information
// objArray = Anytype of object array, like JSON results
// theme (optional) = A css class to add to the table (e.g. <table class="<theme>">
// enableHeader (optional) = Controls if you want to hide/show, default is show
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + array[i][index] + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
// This function creates a details view table with column 1 as the header and column 2 as the details
// Parameter Information
// objArray = Anytype of object array, like JSON results
// theme (optional) = A css class to add to the table (e.g. <table class="<theme>">
// enableHeader (optional) = Controls if you want to hide/show, default is show
function CreateDetailView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
var row = 0;
for (var index in array[i]) {
str += (row % 2 == 0) ? '<tr class="alt">' : '<tr>';
if (enableHeader) {
str += '<th scope="row">' + index + '</th>';
}
str += '<td>' + array[i][index] + '</td>';
str += '</tr>';
row++;
}
}
str += '</tbody>'
str += '</table>';
return str;
}
Standard Table Example Usage:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/SampleRestService",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function(res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Details View Example Usage:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/SampleRestService",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function(res) {
$('#Results').append(CreateDetailView(res,"CoolTableTheme",true)).fadeIn();
}
});
});
JSON to HTML JavaScript Source Code
That’s it, just do you normal jQuery ajax call and you can put your JSON into a HTML Table. This is a great way to test your JSON objects. I’ve tested the JSON to HTML on various object(s) and the results have been pretty good. If you find you need advanced features when your building your HTML table, you should look at something like jqGrid that has paging, sorting, etc…


#1 by Krishna on May 20, 2010 - 11:25 am
Quote
Thanks a lot! I was looking for something similar. I am creating a simple client to query my semantic database and display the result. So the columns of the query result were dynamic(based on the query) and almost all the Jquery plugins were not helpful in my case.
Thanks Again Zach!!!
#2 by AneeshAbe on June 1, 2010 - 3:13 pm
Quote
Hi ,
Your code looks very interesting.
I was trying to test this with my web service but it is getting hanged at var array = JSON.parse(objArray);
I was trying to make a details view.
At success event I am adding as:
$(‘#myDiv’).append(CreateDetailView(result, “CoolTableTheme”, true).fadeIn());
Somehow it is not working.
The json object I am getting from server look like thsi:
{“d”:[{"__type":"acation","id":"001","date":"2010-06-01 00:00:00","iod":"1","mer":"ABC ","tity":"6","ot":"12,500","nt":"75000","ou":"A","rep":"we","perc":"34","ine":"one","year":"2009","ct":"ABC ","alet":"90000","pro":"1500","stats":"ive","crnt":"5000","ter":"AA"}]}
Could you please add an example json object so that we can run this code?
Your help will be appreciated much!
#3 by Zach on June 1, 2010 - 4:24 pm
Quote
The problem is the encoding of your JSON data, the data you posted above is being returned as an object versus a JSON string. To get around this, you just need to make one small change to the code. Here it is.
Before:
var array = JSON.parse(objArray);
After:
var array = typeof objArray != ‘object’ ? JSON.parse(objArray) : objArray;
I’ll update my example now with this change.
#4 by AneeshAbe on June 2, 2010 - 11:04 pm
Quote
Hi Zach,
Your tip worked. Thanks.
However , we cant go forward with this approach for production level application. So I am relying on jtemplate plug in for a start.
As you said, jqGrid looks amazing!
#5 by AneeshAbe on June 7, 2010 - 1:48 pm
Quote
Hi Zach,
When I run the code I get my first header of table as ‘__type’ and content as ‘acation’ which is the object type. How can I remove the first element of the object array?
I tried with shift() but it was not successful. What do you suggest on this?
#6 by Zach on June 7, 2010 - 2:41 pm
Quote
AnneeshAbe,
I going to assume your still using the data in your previous example from the other day. The reason this will not work is because your data is stored in an associative array which is not support in JavaScript. If you want to delete an item from an associative array, use the following syntax ( ex: delete res.d[0]["__type"]; ). In my example, an $.ajax() call would return a JSON response called “res”.
Zach
#7 by AneeshAbe on June 7, 2010 - 10:10 pm
Quote
Hi Zach,
It worked out well!
Thank you..
#8 by surendran on July 15, 2010 - 12:51 pm
Quote
I am new to JSON. I am looking for this kind of a table formating. I am not able to get this code work. Not sure What are the other API files to be included in the header of the html page.
It would be great if you could publish a complete working example with some sample JSON data
thank you
#9 by Zach on July 20, 2010 - 2:28 pm
Quote
Sunrendran,
Sorry you were not able to get the code working, the only thing required to use these functions is jQuery and a JSON string or JavaScript object. If your not familiar with either, it’d probably be best to create a simple example and then expand it out as you understand each new concept.
Here is an example using a JavaScript object (easy to understand):
var objArray = new Array();
var obj1 = new Object;
obj1.Name = 'Zach';
obj1.Email = 'Zachary.Hunter@gmail.com';
objArray.push(obj1);
var obj2 = new Object;
obj2.Name = 'Hcaz';
obj2.Email = 'gmail@Zachary.Hunter.com';
objArray.push(obj2);
$('#results').append(CreateDetailView(objArray));
#10 by Jeff on July 21, 2010 - 2:07 pm
Quote
When I alert out the array all I get is [object,object][object,object][object,object]
How do I drill into the array to get the appropriate data?
#11 by Jeff on July 21, 2010 - 2:21 pm
Quote
Never mind I figured it out. Thanks for the great tutorial.
Just in case anyone is wondering… My JSON data was:
{“d”:[{"__type":"myJQueryTestBed.names","name":"Jeff","title":null,"state":"closed"},{"__type":"myJQueryTestBed.names","name":"Steve","title":null,"state":"closed"},{"__type":"myJQueryTestBed.names","name":"JT","title":null,"state":"closed"}]}
I was able to get my data while looping by doing this:
array[i].name
array[i].state
#12 by Prabu on August 10, 2010 - 7:34 am
Quote
Please can you provide sample html code with example json String.So it will be more helpfull for me…
Thanks in Advance..
Regards
Prabu.N
#13 by Steve on September 1, 2010 - 2:17 am
Quote
Just thinking, rather than building up strings why not create an array representing the table then use the join method. Apparantly its more efficient than concatenation. I will be testing this against a rather large data set and will post the results for all who are interested.
#14 by Zach on September 1, 2010 - 11:47 am
Quote
It really depends on the applicaiton, but going from JSON to an array doesn’t make sense to me. I do agree that building a big table as a string could make the clients browser become unresponsive, I think a better solution is to write an empty table to then DOM and then add rows to the table as you loop over your source data.
Example:
$("some div").append("< table id=’dynamicTable’>< /table>");
— for each row in source data do
$(‘#dynamicTable tr:last’).after(‘< tr>< td>….< /td>< /tr>’);
** You could initially hide the table and show when load is complete.