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

Python读取JSON配置文件值遇KeyError,求正确读取方法

解决JSON配置读取的KeyError问题

你的错误根源是没理清JSON的层级结构:根对象里的settings_data是一个数组,type这类字段在数组的第一个对象里,不是直接在根对象下。而且你代码里的json.dumps再json.loads完全是冗余操作,直接用json.load读取文件更简洁。

正确读取代码

import os
import json
import sys

# 读取JSON配置文件
with open(os.path.join(sys.path[0], "settings.json"), "r", encoding="utf-8") as f:
    settings = json.load(f)  # 直接用json.load读取文件,无需f.read()再loads

# 获取settings_data数组里的第一个配置对象
config = settings["settings_data"][0]

# 读取所需的配置值
amount = config["amount"]
threads = config["threads"]
send_type = config["type"]
id_value = config["id"]

# 测试输出
print(f"amount: {amount}, threads: {threads}, type: {send_type}, id: {id_value}")

额外注意事项

  • 如果settings_data数组可能有多个配置项,可以用循环遍历:
    for config in settings["settings_data"]:
        print(config["amount"], config["threads"])
    
  • 为避免键不存在报错,可使用get方法设置默认值:
    send_type = config.get("type", 1)  # 若type不存在,默认返回1
    

内容的提问来源于stack exchange,提问作者Jane1990

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:55:16