Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function printJSONTable(json){
- // clear the main div holding the table
- $("#content").empty();
- // create an empty table and add it to the main div
- $('<table/>', {
- 'id': 'jsonTable',
- 'html': ''
- }).appendTo('#content');
- $('<tr/>', { // row for headers
- 'html':'',
- 'contentEditable':''
- }).appendTo("#jsonTable");
- // iterate over the json objects
- $.each(json, function (index, element){
- $('<tr/>', { // row for json data
- 'html':'',
- 'contentEditable':''
- }).appendTo("#jsonTable");
- $("#jsonTable th").each(function(){
- $('<td />', {
- 'html':'',
- 'contentEditable':''
- }).appendTo('#jsonTable tr:last')
- })
- // iterate over the key/values of one object
- $.each(Object.keys(this), function(i, key){
- // if the key is not in the first row of the table...
- var keyFound = false;
- var keyIndex;
- $("#jsonTable th").each(function(idx){
- if($(this).text() === key){
- keyFound = true;
- keyIndex = idx + 1;
- }
- })
- // ...generate a new header and new rows
- if(keyFound === false){
- $('#jsonTable').find('tr').each(function(j) {
- // Header row
- if (j === 0) {
- $('<th/>', {
- 'html':key
- }).appendTo(this);
- }else{
- $('<td/>', {
- 'html':''
- }).appendTo(this);
- }
- })
- // see if the object is an array
- if(Object.prototype.toString.call(element[key]) === '[object Array]' ){
- $.each(element[key], function(idx, elem){
- $("#jsonTable td:last").append(this);
- if(idx !== element[key].length - 1){
- $("#jsonTable td:last").append("<br>");
- }
- })
- } else {
- $("#jsonTable td:last").append(element[key]);
- }
- } else {
- if(Object.prototype.toString.call(element[key]) === '[object Array]' ){
- $.each(element[key], function(idx, elem){
- $("#jsonTable tr:last td:nth-child(" +keyIndex + ")").append(this);
- if(idx !== element[key].length - 1){
- $("#jsonTable tr:last td:nth-child(" +keyIndex + ")").append("<br>");
- }
- })
- } else {
- $("#jsonTable tr:last td:nth-child(" +keyIndex + ")").append(element[key])
- }
- }
- });
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement