【问题标题】:how can I get json value select from multiple values with python and jq如何使用 python 和 jq 从多个值中选择 json 值
【发布时间】:2020-03-13 05:54:53
【问题描述】:

我一直在努力处理 json 的问题。我有“unit_number”和“key”值,我想根据 unit_number 和 key 值找到 backing_uuid。我怎么能用python做到这一点?我想像这个 jq 查询,但我以前从未尝试过。我不知道如何在python中调用jq。

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

我有这样的 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
        }
    }
}

【问题讨论】:

    标签: python arrays json python-2.7 jq


    【解决方案1】:
    for thing in dic['guest_disk_facts']:
        if thing['key'] == key and thing['unit_number'] == unit_number:
            print(thing['backing_uuid'])
            break
    

    【讨论】:

      【解决方案2】:

      由于 .unit_number 和 .key 已经是数字,jq 查询将是:

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

      至于将 python 与 jq 一起使用,请参见例如Is there a way to execute jq from python

      【讨论】:

      • 您好,谢谢您的回复,但是我如何在 python 中使用 jq?是这种风格吗:“cat file.json | jq query”?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多