Skip to content

Instantly share code, notes, and snippets.

@shon
Created January 15, 2020 04:27
Show Gist options
  • Save shon/8617da7a78c09abd67490127de86d952 to your computer and use it in GitHub Desktop.
Save shon/8617da7a78c09abd67490127de86d952 to your computer and use it in GitHub Desktop.
TiptapY - Simpler Approach
import json
def convert_any(node):
typ = node.get('type', '')
print('node type: ', typ)
if typ == 'doc':
out = convert_doc(node)
elif typ == 'paragraph':
out = convert_paragraph(node)
elif typ == 'text':
out = convert_text(node)
elif typ == 'bullet_list':
out = convert_list(node)
elif typ == 'list_item':
out = convert_listitem(node)
else:
print('unsupported node', node)
out = ''
return out
def convert_text(node):
text = node['text']
marks = node.get('marks')
if marks:
for mark in marks:
typ = mark.get('type')
if typ == 'bold':
text = f'<strong> {text} </strong>'
if typ == 'italic':
text = f'<i> {text} </i>'
return f'<span> {text} </span>'
def convert_paragraph(node):
out = ''
subnodes = node['content']
for subnode in subnodes:
out += convert_any(subnode)
return f'<p> {out} </p>'
def convert_list(node):
out = ''
subnodes = node['content']
for subnode in subnodes:
out += convert_listitem(subnode)
return f'<ul> {out} </ul>'
def convert_listitem(node):
out = ''
subnodes = node['content']
for subnode in subnodes:
out += convert_any(subnode)
return f'<li> {out} </li>'
def convert_doc(node):
out = ''
subnodes = node['content']
for subnode in subnodes:
out += convert_any(subnode)
return out
def to_html(s):
in_data = json.loads(s)
return convert_any(in_data)
def test():
s = open('tests/data.json').read()
out = to_html(s)
print('============')
print(out)
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment