HtmlJsonConverter

Written by Kuligaposten

HtmlJsonConverter

Javascript HtmlJsonConverter

class HtmlJsonConverter {
  constructor() {}

  htmlToJson(element) {
    const json = {};
    json.tagName = element.tagName.toLowerCase();

    // Extract attributes
    const attributes = element.attributes;
    if (attributes) {
      json.attributes = {};
      for (let i = 0; i < attributes.length; i++) {
        const attr = attributes[i];
        json.attributes[attr.nodeName] = attr.nodeValue;
      }
    }

    // Set text content if provided directly in the element
    const textContent =
      element.childNodes.length === 1 &&
      element.childNodes[0].nodeType === Node.TEXT_NODE
        ? element.textContent.trim()
        : undefined;
    if (textContent) {
      json.textContent = textContent;
    }

    // Extract child elements recursively
    if (element.children.length > 0) {
      json.children = [];
      for (let i = 0; i < element.children.length; i++) {
        const child = element.children[i];
        if (child.nodeType === Node.ELEMENT_NODE) {
          json.children.push(this.htmlToJson(child));
        }
      }
    }

    return json;
  }

  jsonToHtml(json) {
    const element = document.createElement(json.tagName);

    // Set attributes
    if (json.attributes) {
      for (const [key, value] of Object.entries(json.attributes)) {
        element.setAttribute(key, value);
      }
    }

    // Set text content if available
    if (json.textContent !== undefined) {
      element.textContent = json.textContent;
    }

    // Append child elements recursively
    if (json.children) {
      for (const childJson of json.children) {
        const childElement = this.jsonToHtml(childJson);
        element.appendChild(childElement);
      }
    }

    return element;
  }
}

How to use the HtmlJsonConverter

// Example usage:
const converter = new HtmlJsonConverter();

// Convert HTML to JSON
const htmlElement = document.getElementById('example');
const json = converter.htmlToJson(htmlElement);
console.log(json);

// Convert JSON to HTML
const container = document.getElementById('container');
const htmlElementFromJson = converter.jsonToHtml(json);
container.appendChild(htmlElementFromJson);

samplejson

Go back