我正在构建一个 Angular 7 应用程序。
在此应用程序中,我让用户编辑 HTML,然后我希望将其转换为 JSON,以便以有意义的方式存储它。
简而言之,我想获取任何 HTML 代码并将其处理为 JSON 对象。我怎样才能做到这一点?
我会将 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);
.as-console-wrapper {
max-height: 100% !important;
}
<div id="example" class="ex">
<span>Span 1</span>
<span>Span 2</span>
<!-- comment -->
<span>
Span 3
<span>Inner span</span>
</span>
</div>
显然这只是一个粗略的草图,而不是一个完全成熟的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)