【问题标题】:Convert JSON to Elements tree [closed]将 JSON 转换为元素树 [关闭]
【发布时间】:2021-07-21 05:54:15
【问题描述】:

我想将 JSON(对象文字)转换为元素树 HTML。
我还想支持自定义data-* 属性,例如:data-example、data-link 等。

我的 JSON 示例:

{"<>":"div","content":["hello",{"<>":"span","content":["Hello"],"attrs":{"class":"color-red"}}],"attrs":{"class":"flex"}}

现在这是我期望的输出:

<div class='flex'>hello<span class='color-red'>Hello</span></div>

我不知道从哪里开始解决这个问题......

【问题讨论】:

标签: javascript jquery arrays json


【解决方案1】:

JSON 到 HTML 元素树

基本上,关键是使用递归函数。

  • 稍微修改您的初始 JSON 以删除像 "&lt;&gt;" 这样的奇怪属性,而改用 "tag"。
  • 创建两个辅助函数 newEL 和 newTN 以相应地生成具有属性或文本节点的新元素
  • 创建一个递归函数JSON2DF,它将您的JSON(或对象)数据解析到DocumentFragment容器中,以后可以在任何需要的地方使用appended。
  • 如果迭代对象具有 content 数组 - 递归调用 JSON2DOM 在数组中的每个元素上。

const newTN = (text) => document.createTextNode(text);
const newEL = (tag, attr) => {
  const EL = document.createElement(tag);
  if (attr) Object.entries(attr).forEach(([k,v]) => EL.setAttribute(k, v));
  return EL;
};

const JSON2DF = (data, PAR = new DocumentFragment()) => {
  const CH = typeof data === "string" ? newTN(data) : newEL(data.tag, data.attr)
  if (data.content) data.content.forEach(d => JSON2DF(d, CH)); // Recursion!
  PAR.append(CH);
  return PAR;
};

const data = {
  tag: "DIV",
  attr: { class: "flex" },
  content: [
    "Some DIV text",
    {
      tag: "SPAN",
      attr: { class: "color-red", "data-test": "test" },
      content: [
        "Some span text",
      ],
    }
  ],
};

document.body.append(JSON2DF(data));
.color-red { color: red; }

结果如预期:

<div class="flex">
  Some DIV text<span class="color-red">Some span text</span>
</div>

【讨论】:

  • 感谢您的帮助,祝您成功:)
  • 您的代码可以工作,但 (data-example, data-link) 等属性不支持:(
  • @SalarIzadi 在这种情况下,您可以扩展 newEL 函数以解释 "data-*" 并在该新元素的 forEach 循环中使用 EL.setAttribute
  • @SalarIzadi 编辑了代码并修复以支持自定义 data-* 属性。当使用属性而不是节点属性时 - 像最初一样使用"class"(而不是"className")。
  • 谢谢兄弟帮了我​​这么多。祝你成功:)
猜你喜欢
  • 2012-02-08
  • 2014-02-26
  • 2020-01-16
  • 2016-10-14
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 2020-06-16
  • 2021-10-27
相关资源
最近更新 更多