如何在Python Jupyter Notebook中展示可折叠交互的JSON/字典(HTML展示)?
在Jupyter Notebook中交互式折叠展示JSON/字典的方法
当然可以,以下是几种实用的实现方式:
方法一:手动生成可折叠HTML结构
通过结合HTML、CSS和JavaScript,自定义函数将字典/JSON转换为可折叠的交互式结构,完全可控样式和交互逻辑:
from IPython.display import HTML import json def dict_to_collapsible_html(data, level=0): indent = level * 20 html = [] if isinstance(data, dict): html.append(f'<div style="margin-left:{indent}px;">') for key, value in data.items(): html.append(f''' <div style="cursor: pointer; font-weight: bold;" onclick="this.nextElementSibling.style.display = this.nextElementSibling.style.display === 'none' ? 'block' : 'none';"> ▶️ {key} </div> <div style="display: none;"> {dict_to_collapsible_html(value, level+1)} </div> ''') html.append('</div>') elif isinstance(data, list): html.append(f'<ul style="margin-left:{indent}px; list-style-type: disc;">') for item in data: html.append(f'<li>{dict_to_collapsible_html(item, level+1)}</li>') html.append('</ul>') else: html.append(f'<span>{repr(data)}</span>') return ''.join(html) # 示例测试字典 sample_dict = { "name": "Jupyter Demo", "version": "1.0", "settings": { "theme": "dark", "font": {"size": 14, "family": "Monospace"}, "plugins": ["code-highlight", "collapsible-sections"] }, "is_active": True } # 渲染交互式HTML HTML(f''' <style> div {{ font-family: monospace; }} </style> {dict_to_collapsible_html(sample_dict)} ''')
运行后点击带箭头的键名即可展开/折叠子内容,结构清晰且支持自定义样式。
方法二:使用ipytree库构建树形折叠结构
ipytree是专为Jupyter设计的树形组件库,提供成熟的交互式折叠、节点管理功能:
- 先安装依赖:
pip install ipytree jupyter nbextension enable --py ipytree
- 示例代码:
from ipytree import Node, Tree from IPython.display import display def dict_to_tree(data, parent_node=None): if parent_node is None: tree = Tree() parent_node = Node("Root") tree.add_node(parent_node) if isinstance(data, dict): for key, value in data.items(): child_node = Node(key) parent_node.add_node(child_node) dict_to_tree(value, child_node) elif isinstance(data, list): for idx, item in enumerate(data): child_node = Node(f"[{idx}]") parent_node.add_node(child_node) dict_to_tree(item, child_node) else: parent_node.add_node(Node(repr(data))) return tree if parent_node.name == "Root" else None # 生成并展示树形结构 tree = dict_to_tree(sample_dict) display(tree)
该方法支持右键菜单、节点样式修改等进阶操作,适合复杂结构的展示需求。
方法三:利用HTML原生<details>标签快速实现
HTML5的<details>和<summary>标签原生支持折叠功能,无需额外依赖即可快速搭建轻量展示:
from IPython.display import HTML import json def json_to_details_html(data, level=0): indent = level * 4 if isinstance(data, dict): html = [] for key, value in data.items(): html.append(f''' <details style="margin-left:{indent}px;"> <summary style="font-family: monospace; font-weight: bold;">{key}</summary> {json_to_details_html(value, level+1)} </details> ''') return ''.join(html) elif isinstance(data, list): html = [] for idx, item in enumerate(data): html.append(f''' <details style="margin-left:{indent}px;"> <summary style="font-family: monospace;">[{idx}]</summary> {json_to_details_html(item, level+1)} </details> ''') return ''.join(html) else: return f'<p style="margin-left:{indent}px; font-family: monospace;">{repr(data)}</p>' # 渲染展示 HTML(json_to_details_html(sample_dict))
这种方式代码简洁,适合快速实现基础的折叠交互效果。
内容的提问来源于stack exchange,提问作者joshlk
相关产品推荐
相关产品推荐

