Created
September 6, 2011 21:26
-
-
Save fbstj/1199018 to your computer and use it in GitHub Desktop.
HTML object notation, maps JSON to HTML tables and lists
This file contains hidden or 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
// converts HTML tables and lists into JSON/js objects and arrays | |
function HTMLOFF(el) | |
{//reverses the effects of HTMLON | |
function tbl(root) | |
{ | |
var o = {}, rows = $('tbody', root).first().children(), | |
row = rows.first() | |
for(var j = 0; j < rows.length; j++) | |
{ | |
var k = row.children().first(), | |
v = k.next() | |
o[k.text()] = HTMLOFF(v.children().first()) || HTMLOFF(v) | |
row = row.next() | |
} | |
return o | |
} | |
function ul(root) | |
{ | |
var o = [], rows = root.first().children(), | |
row = rows.first() | |
for(var j = 0; j < rows.length; j++) | |
{ | |
var c = row.children(), v | |
if(c.length > 0) | |
v = c.first() | |
else | |
v = row | |
o.push(HTMLOFF(v)) | |
row = row.next() | |
} | |
return o | |
} | |
var i = $(el) | |
if(i.is('table')) | |
return tbl(i) | |
if(i.is('ul')) | |
return ul(i) | |
var o = i.text() | |
return Number(o) || o | |
} |
This file contains hidden or 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
/* | |
this is a script to turn JSON blobs into a HTML object notation I saw somewhere on the internet but have since forgotten the source, so thanks to whoever made this up :D | |
what it does is turn JSON objects into tables with each row being a key-value pair: <tr><th>key</th><td>value</td></tr>, and turns arrays into unordered lists of the elements. | |
*/ | |
// requires jQuery, | |
// HTMLON(json object, jQuery element) | |
function HTMLON(o, e) { | |
function ne(name) { return $(document.createElement(name)); } | |
function nr(i, v) { | |
return ne('tr').append(ne('th').text(i)).append(HTMLON(v, ne('td'))); | |
} | |
if ($.isArray(o)) { | |
var ul = ne('ul'); | |
$.each(o, function(i, v) { | |
ul.append(HTMLON(v, ne('li'))); | |
}); | |
e.append(ul); | |
} | |
else if (typeof o == 'object') { | |
var t = ne('table'); | |
$.each(o, function(i, v) { | |
t.append(nr(i, v)); | |
}); | |
e.append(t); | |
} | |
else if(typeof o == 'function') | |
{ | |
e.append(ne('code').text(o.toString())); | |
} | |
else { | |
e.text(o); | |
} | |
return e; | |
} |
glad very-past-me could help out :3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much, that code snipped saved me a lot of time ^^