python - 使用 for 循环将数据写入 JSON 文件
问题描述
我当前的 sample.json 看起来像这样
{
"clients":[
{
"username":"user1",
"level":"100"
},
{
"username":"user2",
"level":"200"
}
]
}
如何使用 json 库在 Python 中添加第三个用户,使文件最终看起来像这样?
{
"clients":[
{
"username":"user1",
"level":"100"
},
{
"username":"user2",
"level":"200"
},
{
"username":"user3",
"level":"300"
}
]
}
使用这种方法会给我 TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
import json
data= {
"username":"user3",
"level":"300",
}
with open('sample.json') as data_file:
old_data = json.load(data_file)
data = old_data + data
with open('sample.json', 'w') as outfile:
json.dump(data, outfile)
解决方案
old_data['clients'].append(data)
with open('sample.json', 'w') as outfile:
json.dump(old_data, outfile)
当然,old_data
使用不同的名称可能会更好,例如json_data
,即不暗示“未更新”的名称。
推荐阅读
- ruby - 在 method_missing 方法中产生 self 对象(ruby)
- angular - Why page is reloaded after key.enter Angular?
- android - 从 Android 上的无障碍服务获取 ImageView 内容
- c++ - 将 OpenGL 4.5 的东西翻译成 OpenGL 4.0 会使我的程序崩溃
- r - R中间隔内有多少分钟
- ios - 当我们在文本和图像之间切换按钮内容时,如何停止 SwiftUI 更改固定填充?
- python - pre_save 在 mongoengine update_one 中不起作用
- reactjs - React 创建应用程序和 SonarQube 认知复杂性
- c++ - 具有独立子项目的 CMake 项目
- .net-core - 是什么导致了我的 DbUpdateConcurrencyException?