Skip to content

Instantly share code, notes, and snippets.

@SethVandebrooke
Last active May 9, 2019 20:46
Show Gist options
  • Save SethVandebrooke/e8f7eb1afa9f0c3438740286ab96ba11 to your computer and use it in GitHub Desktop.
Save SethVandebrooke/e8f7eb1afa9f0c3438740286ab96ba11 to your computer and use it in GitHub Desktop.
Convert JSON to HTML and HTML to JSON

Two way JSON and HTML conversion

Easily convert JSON to HTML and HTML to JSON using two javascript functions:

JSON_to_HTML()
// and
HTML_to_JSON()

Pass JSON string or object

JSON_to_HTML([
    {
        tagName: "div",
        id: "main",
        children: [
            {
                tagName: "h1",
                id: "mainTitle",
                children: [
                   { text: "Hello World!" }
                ]
            }
        ]
    }
  ]);

Output:

<div id="main"><h1 id="mainTitle">Hello World!</h1></div>

Pass HTML string

HTML_to_JSON(`<div id="main"><h1 id="mainTitle">Hello World!</h1></div>`);

Output:

{
    tagName: "html",
    children: [
        {
            tagName: "head"
        },
        {
            tagName: "body",
            children: [
                {
                    tagName: "div",
                    id: "main",
                    children: [
                        {
                            tagName: "h1",
                            id: "mainTitle",
                            children: [
                            { text: "Hello World!" }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

You can set the 'strip' parameter to only return the children of the body

HTML_to_JSON(`<div id="main"><h1 id="mainTitle">Hello World!</h1></div>`);

Output:

[
    {
        tagName: "div",
        id: "main",
        children: [
            {
                tagName: "h1",
                id: "mainTitle",
                children: [
                   { text: "Hello World!" }
                ]
            }
        ]
    }
  ]
/* example use:
// pass JSON string or object
JSON_to_HTML([
{
tagName: "div",
id: "main",
children: [
{
tagName: "h1",
id: "mainTitle",
children: [
{ text: "Hello World!" }
]
}
]
}
]);
// output:
<div id="main"><h1 id="mainTitle">Hello World!</h1></div>
// pass HTML string
HTML_to_JSON(`<div id="main"><h1 id="mainTitle">Hello World!</h1></div>`);
// output:
{
tagName: "html",
children: [
{
tagName: "head"
},
{
tagName: "body",
children: [
{
tagName: "div",
id: "main",
children: [
{
tagName: "h1",
id: "mainTitle",
children: [
{ text: "Hello World!" }
]
}
]
}
]
}
]
}
// you can set the 'strip' parameter to only return the children of the body
HTML_to_JSON(`<div id="main"><h1 id="mainTitle">Hello World!</h1></div>`);
// output:
[
{
tagName: "div",
id: "main",
children: [
{
tagName: "h1",
id: "mainTitle",
children: [
{ text: "Hello World!" }
]
}
]
}
]
*/
function JSON_to_HTML(json) {
var output = "", parsed;
if (Array.isArray(json)) {
json.forEach(function (item) {
if (typeof item === "object") {
output += JSON_to_HTML(item);
}
});
} else if (typeof json === "object") {
var obj = json;
var tagName = obj.tagName;
if (!tagName && !!obj.text) {
return obj.text;
}
// start the open tag
output += "<"+tagName;
// add attributes if any
for (var k in obj) {
var v = obj[k];
if (typeof v === "string" && k != "tagName" && k != "text") {
output += ' ' + k + '="' + v + '"';
} else {
console.log("attribute must be a string");
}
}
// close the open tag
output += '>';
// nest children elements
if (obj.children) {
output += JSON_to_HTML(obj.children);
}
// add closing tag
output += "</"+tagName+">";
} else if (typeof json === "string") {
try {
parsed = JSON.parse(json);
} catch (e) {
console.log(e);
return null;
}
output += JSON_to_HTML(parsed);
}
return output;
}
function HTML_to_JSON (html, strip) {
var tokenize = html => new DOMParser().parseFromString(html, 'text/html');
function parse(token) {
var node = new Object();
if (token[0]) {
var nodes = [];
console.log("Parsing child node array");
token.forEach(function (token) {
console.log(`Parsing node: `,token);
var parsed = parse(token);
if (parsed) {
nodes.push(parsed);
}
});
return nodes;
} else {
if (token.nodeName == "#document") {
return parse(token.childNodes[0]);
} else if (token.nodeName == "#text") {
var text = token.textContent;
// If there is any text
if (!!text.replace(/\s+/,'')) {
node.text = text;
return node;
}
} else {
// Get tag name
node.tagName = token.localName;
console.log("Node tagName: ",node.tagName);
// Get attributes, if any
if (token.attributes && token.attributes.length > 0) {
for (var index in token.attributes) {
var attr = token.attributes[index];
if (attr.localName != undefined && attr.localName != "undefined") {
node[attr.localName] = attr.value;
console.log(`Node ${node.tagName}: ${attr.localName}=${attr.value}`);
}
}
}
// Get children, if any
if (token.childNodes && token.childNodes.length > 0) {
console.log("Parsing node children");
node.children = parse(token.childNodes);
}
return node;
}
}
}
return strip ? parse(tokenize(html)).children[1].children : parse(tokenize(html));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment