如何在
JMESPath
中使用Python
从下面的数据中提取数组[["S", "2313711"], ["S", "15366545"]]
:
data = {
"categories": [
{
"sport": "S",
"children": [
{"id": "2313711"},
{"id": "15366545"}
]
}
]
}
请注意,子数组的长度可能会有所不同。
到目前为止,我尝试过:
jmespath.search("categories[][ [ sport, children[].id] ][]", data)
# output: [['S', ['2313711', '15366545']]]
这不是我想要的,因为它将所有孩子 ID 分组到一个列表下,而不是为每个孩子 ID 和相应的运动值生成单独的列表。
结合使用
map
和 merge
JMESPath:
expression = jmespath.compile("categories[].children[].merge(`{sport: @.sport}`, @)")
result = jmespath.search(expression, data)
输出:
[{'sport': 'S', 'id': '2313711'}, {'sport': 'S', 'id': '15366545'}]
如果您希望输出为
[["S", "2313711"], ["S", "15366545"]]
,请修改表达式:
expression = jmespath.compile("categories[].children[].['sport', @.sport, 'id', @.id]")
result = jmespath.search(expression, data)