novacisko

html2json

Apr 23rd, 2020
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function html2json(subj) {
  2.     "use strict";
  3.     if (typeof subj == "string") {
  4.         var x = document.createElement("DIV");
  5.         x.innerHTML=subj;
  6.         var res = html2json(x);
  7.         return res["@"];
  8.     } else {
  9.         var res = {};
  10.         res["#"] = subj.tagName;
  11.         var attrs = subj.attributes
  12.         Array.prototype.forEach.call(attrs, x=>{
  13.             res[x.name] = x.value;
  14.         });
  15.         var x = subj.firstChild;
  16.         var a = [];
  17.         while (x) {
  18.             if (x.nodeType == Node.TEXT_NODE) {
  19.                 a.push(x.nodeValue);               
  20.             } else {
  21.                 a.push(html2json(x));
  22.             }
  23.             x = x.nextSibling;
  24.         }
  25.         res["@"] = a;
  26.         return res;
  27.     }
  28. }
  29.  
  30. function json2html(subj) {
  31.     "use strict";
  32.     if (Array.isArray(subj)) {
  33.         return subj.reduce(
  34.                 (a,b)=>{
  35.                     a.appendChild(json2html(b));
  36.                     return a;
  37.                 },document.createDocumentFragment());      
  38.     } else if (typeof subj == "object") {
  39.         var el = document.createElement(subj['#']);
  40.         for (var z in subj) {
  41.             if (z == '#') continue;
  42.             else if (z == '@') el.appendChild(json2html(subj[z]));
  43.             else {
  44.                 el.setAttribute(z, subj[z]);
  45.             }
  46.         }
  47.         return el;
  48.     } else {
  49.         var z = document.createTextNode(subj);
  50.         return z;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment