html-to-json-parser
Version:
This library converts HTML to JSON or JSON to HTML tree
3 lines (2 loc) • 1.16 kB
JavaScript
import{DOMParser as t}from"@xmldom/xmldom";async function e(e,n=!1){return await new Promise((r,o)=>{try{const o={};let s;if("string"==typeof e){const n=(new t).parseFromString(e,"text/xml");n.firstChild&&(s=n.firstChild)}else s=e;const i=(t,e=o)=>{e.type=t.nodeName;const n=t.childNodes;if(null!==n&&n.length){e.content=[];for(let t=0;t<n.length;t++)3===n[t].nodeType?n[t].nodeValue&&e.content.push(n[t].nodeValue):(e.content.push({}),i(n[t],e.content[e.content.length-1]))}if(null!==t.attributes&&t.attributes.length){e.attributes={};for(let n=0;n<t.attributes.length;n++)e.attributes[t.attributes[n].nodeName]=t.attributes[n].nodeValue}};i(s),r(n?JSON.stringify(o):o)}catch(t){o(t)}})}async function n(e,n=!0){return await new Promise((r,o)=>{try{let o=e;"string"==typeof e&&(o=JSON.parse(e));const s=t=>{let e=`<${t.type}`;return t.attributes&&Object.entries(t.attributes).forEach(([t,n])=>{e+=` ${t}="${n}"`}),e+=">",t.content&&t.content.forEach(t=>{e+="string"==typeof t?t:s(t)}),e+=`</${t.type}>`,e},i=s(o);r(n?i:(new t).parseFromString(i,"text/xml"))}catch(t){o(t)}})}export{e as HTMLToJSON,n as JSONToHTML};
//# sourceMappingURL=index.modern.js.map