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

Python向嵌套JSON插入键值对出现KeyError问题求助

解决JSON嵌套对象插入键值对时的KeyError问题

问题场景

现有如下格式的JSON文件:

{
    "A": {
        "A": "2024-07-17 20:06:35.185784",
        "B": "2024-07-17 20:27:15.531860"
    },
    "B": {
        "A": "2024-07-17 20:27:15.531860",
        "B": "2024-07-17 20:27:15.531860"
    }
}

尝试用Python代码为B对应的嵌套对象插入"C": "Some text",编写的代码如下:

with open('/Users/admin/Downloads/files/date.json') as jsonfile:
    data = json.load(jsonfile)

data['B']['C'] = "Some text"        

with open('/Users/admin/Downloads/files/date.json', 'w') as jsonfile:
    json.dump(data, jsonfile, indent=4)

运行后出现KeyError报错:

Ignoring exception in on_voice_state_update
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/Users/admin/Downloads/files/sharedvc.py", line 78, in on_voice_state_update
    data[B][C] = "Some text"

KeyError: 'C'

报错原因

从报错栈的代码行data[B][C] = "Some text"可以看出,实际运行的代码中键名B和C没有用字符串引号包裹。Python会将B和C视为变量去查找,而不是作为字典的字符串键,当找不到对应变量时就会抛出KeyError。

解决方法

1. 修正键名的字符串引号

将代码中的data[B][C]改为data['B']['C'],确保键名是字符串类型:

with open('/Users/admin/Downloads/files/date.json') as jsonfile:
    data = json.load(jsonfile)

# 修正为带引号的字符串键
data['B']['C'] = "Some text"        

with open('/Users/admin/Downloads/files/date.json', 'w') as jsonfile:
    json.dump(data, jsonfile, indent=4)

2. 可选:避免父键不存在的情况

如果担心data['B']可能不存在(比如JSON文件中没有B键),可以用setdefault方法先创建空字典,再插入键值对:

with open('/Users/admin/Downloads/files/date.json') as jsonfile:
    data = json.load(jsonfile)

# 确保B对应的字典存在,不存在则创建空字典
data.setdefault('B', {})['C'] = "Some text"        

with open('/Users/admin/Downloads/files/date.json', 'w') as jsonfile:
    json.dump(data, jsonfile, indent=4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:31:00