Python 3.9调用json.load提取JSON键值返回空数组问题
问题根因
- 你当前代码直接在JSON加载后的顶级字典中查找
created、version键,但从给出的JSON结构来看,顶级字典仅包含section1、section2两个键,目标键实际嵌套在每个section对应的列表内的子字典中。 - 因此判断条件
"created" in data始终为假,追加值的代码从未执行,最终得到空数组。
修正代码
import os import json with open('./output.json', 'r') as f: data = json.load(f) values= [] # 遍历所有顶级分组 for item_list in data.values(): # 遍历分组下的每个条目 for single_item in item_list: if "created" in single_item: print("Key found!") print ("Version: ", single_item["version"], "created at: ", single_item["created"]) values.append(single_item["version"]) print(values)
运行结果
执行上述代码后,values数组的输出为["1.0.0", "1.0.1", "2.0.0", "2.0.1"],和预期结果一致。
内容的提问来源于stack exchange,提问作者jrz
相关产品推荐
相关产品推荐

