Skip to content

Instantly share code, notes, and snippets.

@anabarasan
Last active December 12, 2015 04:08
Show Gist options
  • Save anabarasan/4711965 to your computer and use it in GitHub Desktop.
Save anabarasan/4711965 to your computer and use it in GitHub Desktop.
json formatter script
/*
jsonformatter.js
usage
construct html table out of given JSON
var html = json2html(json);
format json and use output in editable text containers
var formattedJSONText = formatJSON(json,'text');
format json and use output in divs
var formattedJSONText = formatJSON(json,'html');
*/
var formatJSON = function(strJSON, format, indent){
var tab = format == "text" ? " " : "    ";
var CRLF = format == "text" ? "\n" : "<br/>";
var prefix = typeof indent == 'undefined' ? tab : indent;
var array = typeof strJSON == 'object' ? strJSON : JSON.parse(strJSON);
var str = '{' + CRLF;
for (item in array){
if (typeof array[item] != 'object'){
str += prefix + '"' + item + '": "' + array[item] + '",' + CRLF;
} else {
str += prefix + '"' + item + '": ' + formatJSON(array[item], format, prefix + tab) + ',' + CRLF;
}
}
str = str.substring(0,str.length-2) + CRLF;
str += prefix.substring(0, prefix.length-4) + '}';
return str;
}
var json2html = function(strJSON, id){
var array = typeof strJSON == 'object' ? strJSON : JSON.parse(strJSON);
var str = '<table cellspacing=0 cellpadding=0';
str += typeof id !== 'undefined' ? ' id="' + id + '" style="display:none;">' : '>';
var row = 0;
for (item in array){
str += (row % 2 == 0) ? '<tr class="alt">' : '<tr>';
if (typeof array[item] != 'object'){
str += '<td>'+item+' : </td><td>'+array[item]+'</td></tr>';
} else {
var nxtId = pseudoGUID();
str += '<td>'+item+'</td><td><span onClick=toggle(this,"'+nxtId+'")>[+]</span>'+json2html(array[item], nxtId)+'</td></tr>';
}
row++;
}
str += '</table>';
return str;
}
var pseudoGUID = function(){
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
var toggle = function(t,e){
e = document.getElementById(e);
if(e.style.display == 'none'){
e.style.display = '';
} else {
e.style.display = 'none';
}
if (t.innerHTML == '[+]'){
t.innerHTML = '[-]';
} else {
t.innerHTML = '[+]';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment