我有一个采用这种格式的 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"
#I want to insert here "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)
我收到的错误反馈:
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'
刚刚尝试了这个脚本和文件。对我来说工作得很好。
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",
"C": "Some text"
}
}
代码-
import json
with open('C:/Users/krupauliha/file.json') as jsonfile:
data = json.load(jsonfile)
data['B']['C'] = "Some text"
with open('C:/Users/krupauliha/file.json', 'w') as jsonfile:
json.dump(data, jsonfile, indent=4)