我想要更新的.json文件具有以下结构:
那么我该如何更新我的 .json 文件,以确保我的信息被正确添加?
{
"username": "abc",
"statistics": [
{
"followers": 1234,
"date": "2018-02-06 02:00:00",
"num_of_posts": 123,
"following": 123
}
]
}
我想让它插入一个新的统计数据,像这样
{
"username": "abc",
"statistics": [
{
"followers": 1234,
"date": "2018-02-06 02:00:00",
"num_of_posts": 123,
"following": 123
},
{
"followers": 2345,
"date": "2018-02-06 02:10:00",
"num_of_posts": 234,
"following": 234
}
]
}
在处理
with open(filepath, 'w') as fp:
json.dump(information, fp, indent=2)
文件将始终被覆盖。但是我希望将统计信息中的项目添加进去。我尝试了许多可能的方式来读取文件并在后面追加,但从未成功。
数据写入information变量中,就像这样:
information = {
"username": username,
"statistics": [
{
"date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"num_of_posts": num_of_posts,
"followers": followers,
"following": following
}
]
}
那么我该如何更新我的 .json 文件,以确保我的信息被正确添加?
json.reads
, modify,json.dump
- iBugjson.dump
用新对象覆盖文件。 - Alexander