简体   繁体   English

使用 Python 以类似于 bash 中的 JQ 的方式自动进入下一个 JSON 级别

[英]Automatically entering next JSON level using Python in a similar way to JQ in bash

I am trying to use Python to extract pricePerUnit from JSON.我正在尝试使用 Python 从 JSON 中提取 pricePerUnit。 There are many entries, and this is just 2 of them -有很多条目,这只是其中的两个——

{
  "terms": {
    "OnDemand": {
      "7Y9ZZ3FXWPC86CZY": {
        "7Y9ZZ3FXWPC86CZY.JRTCKXETXF": {
          "offerTermCode": "JRTCKXETXF",
          "sku": "7Y9ZZ3FXWPC86CZY",
          "effectiveDate": "2020-11-01T00:00:00Z",
          "priceDimensions": {
            "7Y9ZZ3FXWPC86CZY.JRTCKXETXF.6YS6EN2CT7": {
              "rateCode": "7Y9ZZ3FXWPC86CZY.JRTCKXETXF.6YS6EN2CT7",
              "description": "Processed translation request in AWS GovCloud (US)",
              "beginRange": "0",
              "endRange": "Inf",
              "unit": "Character",
              "pricePerUnit": {
                "USD": "0.0000150000"
              },
              "appliesTo": []
            }
          },
          "termAttributes": {}
        }
      },
      "CQNY8UFVUNQQYYV4": {
        "CQNY8UFVUNQQYYV4.JRTCKXETXF": {
          "offerTermCode": "JRTCKXETXF",
          "sku": "CQNY8UFVUNQQYYV4",
          "effectiveDate": "2020-11-01T00:00:00Z",
          "priceDimensions": {
            "CQNY8UFVUNQQYYV4.JRTCKXETXF.6YS6EN2CT7": {
              "rateCode": "CQNY8UFVUNQQYYV4.JRTCKXETXF.6YS6EN2CT7",
              "description": "$0.000015 per Character for TextTranslationJob:TextTranslationJob in EU (London)",
              "beginRange": "0",
              "endRange": "Inf",
              "unit": "Character",
              "pricePerUnit": {
                "USD": "0.0000150000"
              },
              "appliesTo": []
            }
          },
          "termAttributes": {}
        }
      }
    }
  }
}

The issue I run into is that the keys, which in this sample, are 7Y9ZZ3FXWPC86CZY , CQNY8UFVUNQQYYV4.JRTCKXETXF , and CQNY8UFVUNQQYYV4.JRTCKXETXF.6YS6EN2CT7 are a changing string that I cannot just type out as I am parsing the dictionary.我遇到的问题是,在此示例中,密钥是7Y9ZZ3FXWPC86CZYCQNY8UFVUNQQYYV4.JRTCKXETXFCQNY8UFVUNQQYYV4.JRTCKXETXF.6YS6EN2CT7是一个不断变化的字符串,我不能像我一样输入字典。

I have python code that works for the first level of these random keys -我有适用于这些随机密钥的第一级的 python 代码 -

with open('index.json') as json_file:
    data = json.load(json_file)

json_keys=list(data['terms']['OnDemand'].keys())

#Get the region
for i in json_keys:
    print((data['terms']['OnDemand'][i]))

However, this is tedious, as I would need to run the same code three times to get the other keys like 7Y9ZZ3FXWPC86CZY.JRTCKXETXF and 7Y9ZZ3FXWPC86CZY.JRTCKXETXF.6YS6EN2CT7 , since the string changes with each JSON entry.但是,这很乏味,因为我需要运行相同的代码三次才能获得其他键,如7Y9ZZ3FXWPC86CZY.JRTCKXETXF7Y9ZZ3FXWPC86CZY.JRTCKXETXF.6YS6EN2CT7 ,因为字符串随每个 JSON 条目而变化。

Is there a way that I can just tell python to automatically enter the next level of the JSON object, without having to parse all keys, save them, and then iterate through them?有没有一种方法可以让 python 自动进入 JSON 对象的下一级,而不必解析所有键,保存它们,然后遍历它们? Using JQ in bash I can do this quite easily with jq -r '.terms[][][]' .在 bash 中使用 JQ 我可以用jq -r '.terms[][][]'很容易地做到这一点。

If you are really sure, that there is exactly one key-value pair on each level, you can try the following:如果您真的确定每个级别上只有一个键值对,您可以尝试以下操作:

def descend(x, depth):
    for i in range(depth):
        x = next(iter(x.values()))

    return x

You can use dict.values() to iterate over the values of a dict.您可以使用dict.values()迭代字典的值。 You can also use next(iter(dict.values())) to get a first (only) element of a dict.您还可以使用next(iter(dict.values()))来获取字典的第一个(唯一)元素。

for demand in data['terms']['OnDemand'].values():
    next_level = next(iter(demand.values()))
    print(next_level)

If you expect other number of children than 1 in the second level, you can just nest the fors:如果您期望第二级中的子代数不是 1,则可以嵌套 fors:

for demand in data['terms']['OnDemand'].values():
    for sub_demand in demand.values()
        print(sub_demand)

If you are insterested in the keys too, you can use dict.items() method to iterate over dict keys and values at the same time:如果您也对键dict.items() ,则可以使用dict.items()方法同时迭代 dict 键和值:

for demand_key, demand in data['terms']['OnDemand'].items():
    for sub_demand_key, sub_demand in demand.items()
        print(demand_key, sub_demand_key, sub_demand)

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

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