Created
November 29, 2011 23:44
-
-
Save therealklanni/1407195 to your computer and use it in GitHub Desktop.
Converts a JSON object into a visual HTML representation. This was originally meant to be part of a side-project I was working on and later abandoned. I might end up recycling this code for something in the future.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
json2html = function(o, e) { | |
var ret, obj, n, t = '<ul/>'; | |
if (!e && $('#json_root').length === 0) { | |
e = $(t,{ | |
"id": "json_root", | |
"class": "array" | |
}).appendTo('body') | |
} else if (!e) { | |
e = $('#json_root'); | |
} | |
if ($.type(o) !== "string") { | |
for (k in o) { | |
if (!o.hasOwnProperty(k)) { | |
continue; | |
} | |
switch ($.type(o[k])) { | |
case "array": | |
if ($('#'+e.attr("id")+"_"+k).length === 0) { | |
n = $(t, { | |
"id": e.attr("id")+"_"+k, | |
"class": "parent", | |
"html": '<input type="checkbox">'+k+'</input><br>' | |
}).appendTo(e); | |
} else { n = e; } | |
$.each(o[k], function() { | |
json2html(this, n); | |
}); | |
break; | |
case "object": | |
if ($('#'+e.attr("id")+'_'+k).length === 0) { | |
n = $(t, { | |
"id": e.attr("id")+"_"+k, | |
"class": "parent", | |
"html": '<input type="checkbox">'+k+'</input><br>' | |
}).appendTo(e); | |
} else { n = e; } | |
obj = o[k] | |
for (x in obj) { | |
json2html(JSON.parse('{"'+x+'":"'+x.toString()+'"}'), n); | |
} | |
break; | |
case "null": | |
o[k] = ""; | |
case "string": | |
case "number": | |
case "boolean": | |
if ($('#'+e.attr("id")+'_'+k).length === 0) { | |
n = $('<li/>', { | |
"id": e.attr("id")+"_"+k, | |
"class": "child", | |
"html": '<input type="checkbox">'+k+'</input><br>' | |
}).appendTo(e); | |
} else { n = e; } | |
break; | |
default: | |
console.warn("DEFAULT",k,$.type(o[k])); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment