python Json递归渲染为html

标签 python json recursion

我在尝试使用递归函数将 json 文件转换为 html 渲染时遇到问题。

这是我的 json。

{
"json": [
          {
            "type": "p",
            "children": [
              {
                "type": "text",
                "data": "Lorem Ipsum is simply dummy text "
              },
              {
                "type": "a",
                "attribs": {
                  "href": "http://example.com"
                },
                "children": [
                  {
                    "type": "text",
                    "data": "simply dummy text"
                  }
                ]
              },
              {
                "type": "text",
                "data": " Lorem Ipsum is simply dummy text 2"
              }
            ]
          },
          {
            "type": "p",
            "children": [
              {
                "type": "text",
                "data": "second Lorem Ipsum is simply dummy text"
              }
            ]
          },
          {
            "type": "div",
            "children": [
              {
                "type": "text",
                "data": "Third Lorem Ipsum is simply dummy text"
              }
            ]
          },
          {
            "type": "outstream-1"
          }
        ]
}

我需要一个嵌套函数,它将返回其子数据值的标签并从父标签渲染。

以下是我的输出:但 outstream-1 不会显示在 html 列表中。

<p>Lorem Ipsum is simply dummy text <a>simply dummy text</a> Lorem Ipsum is simply dummy text 2</p>
<p>second Lorem Ipsum is simply dummy text</p>
<div>Third Lorem Ipsum is simply dummy text</div>

我尝试了以下方法来获取数据,但它对我没有帮助。

def json_render(body_data):
    allow_tags = [
        'p', 'div']
    cdata = '';
    for tag_type in body_data:

        tag = tag_type['type']    
        if tag_type['type'] in allow_tags:
            tag = tag_type['type']
            data = ""
            if tag_type['children']:
                data += child_data(tag_type['children'])
        cdata += f'<{tag}>' \
        f'{data}' \
        f'</{tag}>'

    return cdata

def child_data(data, name="",test=""):
    out = dict()
    if type(data) is dict:
        for a in data:
            child_data(data[a], f'{name}{a}_',"")
    elif type(data) is list:        
        i = 0
        for a in data:
            #test += parse_data(a)
            child_data(a, f'{name}{i}_',"")
            if a['type'] == 'text':
                if 'data' in a:    
                    test+=a["data"]
            i += 1
    return test 

这会返回以下结果。它缺少 anchor 文本。

<p>Lorem Ipsum is simply dummy text Lorem Ipsum is simply dummy text 2</p>
<p>second Lorem Ipsum is simply dummy text</p>
<div>Third Lorem Ipsum is simply dummy text</div>

最佳答案

您可以使用递归:

data = {'json': [{'type': 'p', 'children': [{'type': 'text', 'data': 'Lorem Ipsum is simply dummy text '}, {'type': 'a', 'attribs': {'href': 'http://example.com'}, 'children': [{'type': 'text', 'data': 'simply dummy text'}]}, {'type': 'text', 'data': ' Lorem Ipsum is simply dummy text 2'}]}, {'type': 'p', 'children': [{'type': 'text', 'data': 'second Lorem Ipsum is simply dummy text'}]}, {'type': 'div', 'children': [{'type': 'text', 'data': 'Third Lorem Ipsum is simply dummy text'}]}, {'type': 'outstream-1'}]}
def render(d):
   def build_tag(t):
      if t['type'] == 'text':
         return t['data']
      attrs = ''.join(f' {a}="{b}"' for a, b in t.get("attribs", {}).items())
      return f'<{t["type"]}{attrs}>{render(t.get("children", []))}</{t["type"]}>\n'
   return ''.join(build_tag(i) for i in d)

print(render(data['json']))

输出:

<p>Lorem Ipsum is simply dummy text <a href="http://example.com">simply dummy text</a>
 Lorem Ipsum is simply dummy text 2</p>
<p>second Lorem Ipsum is simply dummy text</p>
<div>Third Lorem Ipsum is simply dummy text</div>
<outstream-1></outstream-1>

关于python Json递归渲染为html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61974967/

相关文章:

python - Paramiko:收集输出的 ssh.exec_command 表示打开 channel 作为响应

python - 如何创建返回列表包含字符串的类型提示?

python - 在 Python 3.5.1 中酸洗 ParseResult 时出错

java - GSON。如何将json对象转换为json数组?

c# - 如何使用 yield break 跳出递归 IEnumerable<T> 循环?

c - 如何避免在这个递归函数中使用malloc?

javascript - 使用python检索动态网站的源(绕过onclick)

java - 生成json树时出现StackOverflowError

java - 使用递归打印出收敛和发散的数字序列时遇到问题

javascript - 如何使用Vue js从JSON文件获取数据?