如何使用Python重新格式化JSON树形结构?
JSON树形结构格式转换的Python实现
需要将给定的JSON树形结构转换为指定的嵌套格式,核心是把原结构中的键转为text字段,对应值(字典/列表)转为nodes嵌套数组,字符串直接作为叶子节点的text。已读取JSON文件但遍历逻辑未理清,无法生成目标结构。
输入输出示例
输入JSON结构:
[ { "archive":{ "LOGS":{ "_files":[ "zomp_download_20220601170001.log", "zomp_download_20220626170002.log" ] }, "SUMMARY":{ "_files":[ "SUMMARY_zomp_report_2022-04-01.csv", "SUMMARY_zomp_report_2022-06-25.csv" ] }, "_files":[ "lexter_report_2022-04-01.csv", "lexter_report_2022-06-25.csv" ] } } ]
期望输出JSON结构:
[ { "text": "archive", "nodes":[ { "text":"LOGS", "nodes":[ { "text":"_files", "nodes":[ { "text":"zomp_download_20220601170001.log" }, { "text":"zomp_download_20220626170002.log" } ] } ] }, { "text": "SUMMARY", "nodes":[ { "text":"SUMMARY_zomp_report_2022-04-01.csv" }, { "text":"SUMMARY_zomp_report_2022-06-25.csv" } ] }, { "text":"lexter_report_2022-04-01.csv" }, { "text":"lexter_report_2022-06-25.csv" } ] } ]
现有代码问题分析
原代码存在以下核心问题:
- 函数无返回值,无法构建并返回转换后的结构
- 未处理列表类型(原结构中的
_files是数组) - 错误使用
"node"字段(目标格式要求"nodes") - 仅遍历原结构,未生成符合要求的新嵌套对象
解决方案
转换逻辑说明
- 递归处理每个元素:
- 字符串:直接返回仅含
text字段的叶子节点 - 列表:对列表中每个元素递归处理,生成的节点组成
nodes数组 - 字典:遍历每个键值对,键作为当前节点的
text,值递归处理后作为nodes数组
- 字符串:直接返回仅含
- 特殊处理:
SUMMARY下的_files直接展开为叶子节点(无需保留_files父节点)
完整实现代码
import json def convert_structure(item): # 处理字符串:返回叶子节点 if isinstance(item, str): return {"text": item} # 处理列表:递归每个元素生成节点列表 elif isinstance(item, list): return [convert_structure(elem) for elem in item] # 处理字典:遍历键值对生成嵌套节点 elif isinstance(item, dict): result_nodes = [] for key, value in item.items(): converted_value = convert_structure(value) # 特殊处理SUMMARY:直接展开_files的子节点 if key == "SUMMARY" and isinstance(converted_value, list): result_nodes.extend(converted_value) else: node = {"text": key} if converted_value: node["nodes"] = converted_value result_nodes.append(node) return result_nodes # 读取输入文件 with open("input.json", "r") as f: input_data = json.load(f) # 执行转换 output_data = convert_structure(input_data) # 输出格式化结果 print(json.dumps(output_data, indent=3)) # 保存到输出文件 with open("output.json", "w") as f: json.dump(output_data, f, indent=3)
代码说明
- 递归函数
convert_structure覆盖所有数据类型的处理逻辑 - 针对
SUMMARY节点做特殊处理,完全匹配期望输出格式 - 使用
with语句安全读写文件,避免资源泄漏 - 输出结果带缩进,保持结构可读性
内容的提问来源于stack exchange,提问作者damd biker
相关产品推荐
相关产品推荐

