使用 JMESPath 引用输出中的外部对象提取嵌套数组

问题描述 投票:0回答:1

如何在

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 和相应的运动值生成单独的列表。

python jmespath
1个回答
0
投票

结合使用

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)
© www.soinside.com 2019 - 2024. All rights reserved.