【问题标题】:python extract key from json file doesn't workpython从json文件中提取密钥不起作用
【发布时间】:2022-06-11 21:25:38
【问题描述】:

我是 python 新手,我正在使用 python 3.9.13 尝试从 json 文件中的现有键中提取值。 我知道json.load() 函数输出一个字典,所以在我的代码的最后一部分我在字典中搜索。

这是我的python代码:

import os
import json

with open('./output.json', 'r') as f:
  data = json.load(f)

values= []

if "created" in data:
    print("Key found!")
    print ("Version: ", data["version"], "created at: ", data["created"])
    values.append(data["version"])

print(values)

这是我正在读取的 output.json 文件:

{
  "section1": [
    {
      "name": "name1",
      "version": "1.0.0",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.22",
      "type": "application",
      "created": "2022-05-03T11:20:45Z"
    },
    {
      "name": "name1",
      "version": "1.0.1",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.22",
      "type": "application",
      "created": "2022-04-20T13:55:16Z"
    }
  ],
  "section2": [
    {
      "name": "name2",
      "version": "2.0.0",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.17",
      "type": "application",
      "created": "2022-01-25T07:58:09Z"
    },
    {
      "name": "name2",
      "version": "2.0.1",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.17",
      "type": "application",
      "created": "2022-01-18T07:08:38Z"
    }
  ]
}

我希望我的数组 values 是:

[1.0.0, 1.0.1, 2.0.0, 2.0.1]

但是我的输出是一个空数组,我不知道为什么。

非常感谢您的帮助!

【问题讨论】:

  • print data 你会发现它是一个字典,其键映射到一个列表,其中包含一个以version 为键的字典。相应地调整您的代码。
  • data 是外部字典,使用"section1" 之类的键,您必须遍历外部字典中的值,这是您的内部字典,然后您可以像 values.append(inner["version"])
  • 只是为了澄清,created 键有什么意义吗?也就是说,您似乎只关心 version 键的值,您是否还需要检查 created 键是否存在?
  • 如果您的期望值[1.0.0, 1.0.1, 2.0.0, 2.0.1] 那么为什么这些打印声明print("Key found!") print ("Version: ", data["version"], "created at: ", data["created"]) values.append(data["version"])。最简单的在线shell脚本是for i in 1 2; do cat output.json | jq .section$i[].version ; done

标签: python json python-3.x


【解决方案1】:

首先,假设datadict 类型,如上所述从JSON 填充:

data = json.load(f)

那么实现所需输出的最简单方法是使用嵌套的list 理解,如下所示:

>>> [dct['version'] for lst in data.values() for dct in lst]
['1.0.0', '1.0.1', '2.0.0', '2.0.1']

请注意,上面的list 理解基本上相当于两个for 循环:

result = []
for lst in data.values():
    for dct in lst:
        result.append(dct['version'])

如果您需要专门检查是否存在 "created" 键,或者如果您需要验证您正在迭代 listdict 类型,例如,您可以改用以下方法:

result = [dct['version'] for lst in data.values() if isinstance(lst, list)
          for dct in lst if isinstance(dct, dict) and 'created' in dct]

【讨论】:

    【解决方案2】:

    您不尊重字典层次结构,当您调用字典中的键时,它不会遍历该字典的所有级别...

    这是完成这项工作的代码的更改版本:

    import os
    import json
    
    with open('./output.json', 'r') as f:
        json_dict = json.load(f)
    
    values= []
    
    for section in json_dict.values():
        for el in section:
            print("Key found!")
            print ("Version: ", el["version"], "created at: ", el["created"])
            values.append(el["version"])
    
    print(values) 
    

    输出:

    Key found!
    Version:  1.0.0 created at:  2022-05-03T11:20:45Z
    Key found!
    Version:  1.0.1 created at:  2022-04-20T13:55:16Z
    Key found!
    Version:  2.0.0 created at:  2022-01-25T07:58:09Z
    Key found!
    Version:  2.0.1 created at:  2022-01-18T07:08:38Z
    ['1.0.0', '1.0.1', '2.0.0', '2.0.1']
    

    【讨论】:

      【解决方案3】:

      你的代码可能是这样的:

      import os
      import json
      
      with open('./output.json', 'r') as f:
        data = json.load(f)
      
      values= []
      for section in data:
          for x in range(len(data.values())):
              if "created" in data[section][x]:
                  print("Key found!")
                  print ("Version: ", data[section][x]["version"], "created at: ", data[section][x]["created"])
                  values.append(data[section][x]["version"])
      
      print(values)
      

      【讨论】:

      • 看起来在这里可能不需要使用range 循环
      • for item in section 会更好,然后只需 item["version"]
      • 还有data 是一个字典,如果你这样做for section in data 那么section 是一个键名,所以len(section) 会给你键名字符串的长度,而不是项目数。最好for section in data.values()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 2017-12-18
      相关资源
      最近更新 更多