【问题标题】:python Json recursively render to htmlpython Json递归渲染到html
【发布时间】:2020-09-10 11:19:00
【问题描述】:

我在尝试创建递归函数时遇到问题,因此我可以将 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 

这将返回以下结果。它缺少锚文本。

<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>

【问题讨论】:

  • 到目前为止你尝试了什么,你能告诉我们。

标签: python json recursion


【解决方案1】:

一个简单的递归应该可以为您完成。这也适用于属性。

它也适用于外流编辑。

def rec(d):
    attribs = ' '.join([f"{k}='{v}'" for (k, v) in d['attribs'].items()]) if 'attribs' in d else ''
    ans = [f'<{d["type"]} {attribs}'.strip() + '>']

    for child in d.get('children', []):
        ans.append(child['data']) if child['type'] == 'text' else ans.append(rec(child))

    ans.append('</{}>'.format(d['type']))
    return ''.join(ans)


for child in d['json']:
    print(rec(child)) # Or you may append it to any other list or container

#Output
<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>

【讨论】:

  • 谢谢兄弟,您的帮助。上面的答案解决了我的目的。
【解决方案2】:

你可以使用递归:

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>

【讨论】:

  • 你能帮我多一点吗?我正在更新我的 json 格式。
猜你喜欢
  • 2016-11-30
  • 1970-01-01
  • 2020-09-08
  • 2014-01-31
  • 2014-10-25
  • 2018-06-14
  • 2011-06-01
  • 1970-01-01
  • 2021-03-10
相关资源
最近更新 更多