Skip to content

Instantly share code, notes, and snippets.

@christopherdebeer
Created October 28, 2011 17:04
Show Gist options
  • Select an option

  • Save christopherdebeer/1322780 to your computer and use it in GitHub Desktop.

Select an option

Save christopherdebeer/1322780 to your computer and use it in GitHub Desktop.
json2html
var testJSON = {
div: {
attributes: {
class: ["wrapper"],
id: "wrapper",
},
innerHTML: {
h1: {
attributes: {
class: ["hd", "bold"]
},
innerHTML: "headline"
},
p: {
attributes: {
class: "txt"
},
innerHTML: {
span: {
attributes:{
class: "emphasize"
},
innerHTML: "more text"
},
text: "this should be a text node",
strong: {
innerHTML: "i am strong"
}
}
},
img: {
attributes: {
src: "/images/coolPicBro.gif",
alt: "Cool story Bro"
}
}
}
}
}
json2html = function (json, container) {
// if container has been parsed then create a new element: container
if (container) { var el = $("<" + container + "/>");}
// otherwise its the grandparent element: html
else { var html; }
$.each(json, function(key,val){
// if it has attributes then apply them
if (key == "attributes") {
$.each(val, function (attr,value) {
// if its an array of values
if (typeof value == "object" && value.length) {
// then itterate through them and apply with spaces between
var allValues = "";
for (var i in value) {
allValues += (value[i] + " ");
}
el.attr(attr,allValues);
} else {
// else set the attribute to the value
el.attr(attr,value);
}
});
// if it has innerHTML
} else if (key == "innerHTML") {
// if its a text node
if (typeof val == "string") {
// then set the contents to the vlaue of the text node
el.html(val)
} else {
// else concatinate its children recursivly and apply them as innerHTML
$.each(val, function(elem, value) {
// if its a text node then append it
if (typeof value == "string") {
el.append($(document.createTextNode(value)));
// else recursivly get the markup of the element and then append it
} else {
el.append(json2html(value, elem));
}
});
}
// if its an element
} else {
// if its the original/container
if (!container) {
// then assign it to the "global" html
html = json2html(val, key);
} else {
// else return recursivly
return json2html(val, key);
}
}
});
if (!container) {
// finish
return html;
} else {
// return the element recursivly
return el;
}
}
console.log(json2html(testJSON));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment