如何将 HTML 代码转换为 JSON 对象?

Mar*_*enn 4 html javascript json angular

我正在构建一个 Angular 7 应用程序。在这个应用程序中,我让用户编辑 HTML,然后我想将其转换为 JSON 以一种有意义的方式存储它。

简而言之,我想将任何 HTML 代码处理成一个 JSON 对象。我怎样才能做到这一点?

T.J*_*der 6

我会将 HTML 解析为 DOM(您可以在客户端或服务器端执行该操作),然后将我关心的 DOM 的各个方面序列化为一个对象,然后我将在其上使用JSON.stringify(如果您真的想要JSON)。

例如:

function converter(dom) {
    if (dom.nodeType === Node.TEXT_NODE) {
        return dom.nodeValue;
    }
    if (dom.nodeType === Node.DOCUMENT_NODE) {
        dom = dom.documentElement;
    }
    const obj = {};
    obj.nodeType = dom.nodeType;
    if (dom.nodeType === Node.ELEMENT_NODE) {
        obj.tagName = dom.tagName;
        obj.attributes = []; // Array.from(obj.attributes) gives us a lot of things we don't want
        for (let i = 0, len = dom.attributes.length; i < len; ++i) {
            const attr = dom.attributes[i];
            obj.attributes.push({name: attr.name, value: attr.value});
        }
        obj.children = [];
        for (let child = dom.firstChild; child; child = child.nextSibling) {
            obj.children.push(converter(child));
        }
    } else {
        obj.nodeValue = dom.nodeValue;
    }
    return obj;
}
const json = JSON.stringify(converter(document.getElementById("example")), null, 4);
console.log(json);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
    max-height: 100% !important;
}
Run Code Online (Sandbox Code Playgroud)
<div id="example" class="ex">
  <span>Span 1</span>
  <span>Span 2</span>
  <!-- comment -->
  <span>
    Span 3
    <span>Inner span</span>
  </span>
</div>
Run Code Online (Sandbox Code Playgroud)

显然,这只是一个粗略的草图,而不是一个完全成熟的解决方案。