Last active
August 29, 2015 14:20
-
-
Save dennishall1/5168b7d28d9ff77824dd to your computer and use it in GitHub Desktop.
HTML to JSON
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
var el = document.getElementById("test-node"); | |
var json = marshal(el, {}); | |
document.write('<pre>' + JSON.stringify(json).replace(/\}/g, "}\n") + '</pre>'); | |
function marshal(element, object) { | |
var scope; | |
each(element.attributes, function(attr){ | |
if(attr.nodeName === 'data-prop'){ | |
object[attr.nodeValue] = element.innerText || element.src; | |
} | |
if(attr.nodeName === 'data-scope'){ | |
scope = attr.nodeValue; | |
} | |
}); | |
each(element.childNodes, function(childNode){ | |
if(childNode.nodeType === 1){ | |
if(scope){ | |
if(object[scope]){ | |
if(!(object[scope] instanceof Array)){ | |
object[scope] = [object[scope]]; | |
} | |
object[scope].push(marshal(childNode, {})); | |
} else { | |
object[scope] = marshal(childNode, {}); | |
} | |
} else { | |
marshal(childNode, object); | |
} | |
} | |
}); | |
return object; | |
} | |
function each(list, fn){ | |
for(var i = 0; i < list.length; i++) { | |
fn(list[i], i); | |
} | |
} |
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
<!doctype html> | |
<html> | |
<head> | |
<title>HTML 2 JSON</title> | |
</head> | |
<body> | |
<div id="test-node"> | |
<h2 data-prop="header">This is the header</h2> | |
<div data-scope="tab"> | |
<img data-prop="src" src="https://placeimg.com/640/480/any"> | |
<h3 data-prop="header">sub header</h3> | |
<div data-prop="body"> | |
body text | |
</div> | |
</div> | |
<div data-scope="tab"> | |
<img data-prop="src" src="https://placeimg.com/640/480/any"> | |
<h3 data-prop="header">sub header</h3> | |
<div data-prop="body"> | |
body text | |
</div> | |
</div> | |
</div> | |
<script src="html2json.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment