Python如何通用提取混合类型嵌套字典中的coords坐标数据
实现方案
可以实现,通过递归深度遍历所有嵌套的字典、列表结构,全局匹配coords字段即可,完全不依赖固定层级结构。
完整代码
import json def extract_coords(data): coords_list = [] # 递归遍历函数 def traverse(node): # 处理字典类型节点 if isinstance(node, dict): # 存在coords字段就添加到结果列表 if 'coords' in node: coords_list.append(node['coords']) # 遍历字典所有值继续递归检查 for value in node.values(): traverse(value) # 处理列表类型节点 elif isinstance(node, list): # 遍历列表所有元素继续递归检查 for item in node: traverse(item) # 先将JSON字符串解析为Python对象 parse_data = json.loads(data) traverse(parse_data) return coords_list # 测试示例 data = '{"foo": {"type": "geo", "coords": [2, 3], "children": [{"type": "geo", "coords": [4, 1], "children": [{"type": "bar", "children": [{"type": "geo", "coords": [8, 4]}]}, {"type": "geo", "coords": [3, 2]}]}]}}' print(extract_coords(data)) # 输出结果:[[2, 3], [4, 1], [8, 4], [3, 2]]
方案说明
- 不需要提前预知结构层级,不管
coords字段藏在多深的嵌套里都能匹配到 - 同时兼容字典、列表两种嵌套容器的场景,覆盖绝大多数JSON解析后的结构场景
- 逻辑简单易修改,如果后续要提取其他字段,只需要把判断的键名替换即可
内容的提问来源于stack exchange,提问作者chirag
相关产品推荐
相关产品推荐

