See my solution working here:
JSON to HTML table (jQuery) - JSFiddle[
^]
Markup:
<table id="myTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>EmailId</th>
<th>MobileNo</th>
<th>City</th>
<th>image</th>
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript:
Note this line is important to find the correct place in the table markup to append the html row (should work for nested tables)
$("#myTable > tbody:last-child")
var data =
[{
"Id":1,
"Name":"Joe",
"EmailId":"joe@email.com",
"MobileNo":"447890111111",
"City":"London"
},
{
"Id":2, "Name":"Tony",
"EmailId":"tony@email.com",
"MobileNo":"447890111112",
"City":"London"
}];
var rowTemplate =
"<table><tbody><tr>"+
"<td>[Id]</td>"+
"<td>[Name]</td>"+
"<td>[EmailId]</td>"+
"<td>[MobileNo]</td>"+
"<td>[City]</td>"+
"<td>[Image]</td>"+
"</tr></tbody></table>";
$(document)
.ready
(
function() {
$.each(data, function(index,value) {
$("#myTable > tbody:last-child").append(GetDataBoundHtml(value));
});
}
)
function GetDataBoundHtml(employee){
var regMap = {
Id:employee.Id,
Name:employee.Name,
EmailId:employee.EmailId,
MobileNo:employee.MobileNo,
City:employee.City
};
var reg = /\[Id\]|\[Name\]|\[EmailId\]|\[MobileNo\]|\[City\]/g;
var htmlRow = rowTemplate;
return htmlRow.replace(reg,function(matched){
var formattedMatch = matched.replace(/\[|\]/g,"");
console.log(formattedMatch);
return regMap[formattedMatch];
});
};
Output:
Id Name EmailId MobileNo City image
1 Joe joe@email.com 447890111111 London [Image]
2 Tony tony@email.com 447890111112 London [Image]