Once you have retrieved the JSON result, you can transform it into Markdown by following these steps:
- Build a Tree Structure: The raw JSON contains a flat list of nodes with
parent_id references. Use a recursive function to build a hierarchical tree. - Define Parsing Rules: Create a function to map node types (e.g.,
Text, Title, Table, Figure) to Markdown syntax. - Flatten the Tree: Recursively traverse the tree to generate a single Markdown string.
Implementation Example
def rule(node, depth):
txt = ""
if node["type"] == "Text":
txt = node["text"]
elif node["type"] == "Title":
title_level = "#" * depth
txt = f"{title_level} {node['text']}"
elif node["type"] in ("Table", "Figure"):
txt = f"\n```{'table' if node['type'] == 'Table' else 'figure'}\n"
txt += node.get("vlm_understanding", node["text"]) + "\n```\n"
return f"\n{txt}\n"
def tree_flat(tree, depth=1):
rst = ""
for node in tree:
rst += rule(node, depth)
if node.get("type") == "Title":
rst += tree_flat(node["children"], depth + 1)
return rst
def build_tree(nodes, parent_id=-1):
tree = []
for node in nodes:
if node["parent_id"] == parent_id:
children = build_tree(nodes, node["id"])
node["children"] = children
tree.append(node)
return tree
# Usage:
# 1. Build tree from JSON
tree = build_tree(json_data.get("data", {}).get("task_result", {}).get("nodes", []))
# 2. Convert to Markdown
rst = tree_flat(tree)
print(rst)