包含JSON文件代码的代码:Python(假设附加一个新用户和余额(:
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)['user_list']
data['user_list']
data.append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)
Json(代码附加的对象(:
{
"user_list": [
{
"user": "<@!672986823185661955>",
"balance": 400
},
{
"user": "<@!737747404048171043>",
"balance": 500
}
],
}
错误(执行代码后出现回溯错误(:
data = json.load(file)['user_list']
KeyError: 'user_list'
解决方案如下:
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)
data['user_list'].append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)