You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 23:42:25