Skip to content

JSON to HTML JQuery Converter

January 25, 2016

After fumbling to find a JSON convert to HTML using JQuery, I have finally found useful piece of code for reading a list of JSON objects and sets it to a HTML table for output. It is useful for calling AJAX in JQuery for MVC C# controllers which returns a JSON object and in return the AJAX can translate the JSON object to HTML. Here's the code.

var myList = [{"name" : "abc", "age" : 50}, {"age" : "25", "hobby" : "swimming"}, {"name" : "xyz", "hobby" : "programming"}]; // Builds the HTML Table out of myList. function buildHtmlTable(selector) { var columns = addAllColumnHeaders(myList, selector); for (var i = 0 ; i < myList.length ; i++) { var row$ = $('<tr/>'); for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) { var cellValue = myList[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(myList) { var columnSet = []; var headerTr$ = $('<tr/>'); for (var i = 0 ; i < myList.length ; i++) { var rowHash = myList[i]; for (var key in rowHash) { if ($.inArray(key, columnSet) == -1){ columnSet.push(key); headerTr$.append($('<th/>').html(key)); } } } $(selector).append(headerTr$); return columnSet; }​


<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: