简体   繁体   English

如何使用 python 和 jq 从多个值中获取 json 值 select

[英]how can I get json value select from multiple values with python and jq

I have been struggling with json stuff.我一直在努力解决 json 的问题。 I have "unit_number" and "key" values and I want to find backing_uuid based on the unit_number and key values.我有“unit_number”和“key”值,我想根据 unit_number 和 key 值找到 backing_uuid。 How can I do that with python?我怎么能用 python 做到这一点? I think like this jq query but I've never tried before.我想像这个 jq 查询,但我以前从未尝试过。 I don't know how can I call jq in python.我不知道如何在 python 中调用 jq。

jq .guest_disk_facts[] |  select(any(.attributes[]?; .unit_number=="2" and .key" == "2002")).backing_uuid and output: 9000da43-8471-57a6-8b18-4425a356b3cb

I have json file like this:我有这样的 json 文件:

{
    "changed": false,
    "failed": false,
    "guest_disk_facts": {
        "0": {

            "backing_uuid": "9000da43-8471-57a6-8b18-92381ab3c3f6",
            "key": 2000,
            "unit_number": 0
        },
        "1": {
            "backing_uuid": "9000da43-8471-57a6-8b18-2788c2398ba7",
            "key": 2001,
            "unit_number": 1
        },
        "2": {
            "backing_uuid": "9000da43-8471-57a6-8b18-4425a356b3cb",
            "key": 2002,
            "unit_number": 2
        }
    }
}
for thing in dic['guest_disk_facts']:
    if thing['key'] == key and thing['unit_number'] == unit_number:
        print(thing['backing_uuid'])
        break

Since.unit_number and.key are already numbers, the jq query would be:由于 .unit_number 和 .key 已经是数字,jq 查询将是:

.guest_disk_facts[]
| select(.unit_number==2 and .key == 2002).backing_uuid

As for using python with jq, see eg Is there a way to execute jq from python至于将 python 与 jq 一起使用,请参见例如Is there a way to execute jq from python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM