如何用Python的JMESPath库展平字典列表中的嵌套数组?
可以用JMESPath实现该转换,具体方法如下
核心思路
利用JMESPath的数组展开和对象构造能力,遍历原始列表中的每个对象,将其examples数组拆分为单个元素,每个元素对应一个新字典,同时按需调整kind字段的取值(如将vehicles转为vehicle)。
具体实现步骤
编写JMESPath表达式
表达式逻辑:[]:遍历原始列表中的每个对象{kind: (kind == 'vehicles' ? 'vehicle' : kind), example: examples[]}:为每个对象构造新结构——kind字段根据原字段值做条件替换,example字段展开原examples数组的每个元素- 末尾的
[]:将所有生成的嵌套结构展平为一维列表
最终表达式:
[].{kind: (kind == 'vehicles' ? 'vehicle' : kind), example: examples[]}[]Python代码示例
先确保已安装JMESPath库:pip install jmespath然后编写代码:
import jmespath import json # 原始JSON数据 raw_json = ''' [ { "kind": "vehicles", "examples": ["car", "helicopter"] }, { "kind": "stars", "examples": ["blue", "red", "neutron"] } ] ''' # 解析JSON data = json.loads(raw_json) # 执行JMESPath查询 result = jmespath.search("[].{kind: (kind == 'vehicles' ? 'vehicle' : kind), example: examples[]}[]", data) # 打印格式化后的结果 print(json.dumps(result, indent=2))输出结果
运行代码后会得到你需要的结构:[ { "kind": "vehicle", "example": "car" }, { "kind": "vehicle", "example": "helicopter" }, { "kind": "stars", "example": "blue" }, { "kind": "stars", "example": "red" }, { "kind": "stars", "example": "neutron" } ]
内容的提问来源于stack exchange,提问作者a693673
相关产品推荐
相关产品推荐

