python Json recursively render to html

Viewed 97

I'm having trouble with a recursive function that i'm trying to make so i can transform a json file to html render.

This is my 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"
          }
        ]
}

I need a nested function which will return with tags of it's children data value and render from parent tags.

The following is my output: but outstream-1 will not show in html list.

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

I have tried the following way to get the data but it does not help me.

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 

this return me the following result. It missing the anchor text.

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

You can use recursion:

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']))

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>

A simple recursion should do it for you. This one works with attributes as well.

It also works with the outstream edit.

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