我在本地服务器中保存了一个json文件,例如:
{
"user": "user1",
"id": "21779"
}
我想在这个json文件中写入另一个dict,我需要这样的新内容:
{
{
"user": "user1",
"id": "21779"
},
{
"user": "user2",
"id": "21780"
}
}
或:
[
{
"user": "user1",
"id": "21779"
},
{
"user": "user2",
"id": "21780"
}
]
我尝试使用json.dump()添加新元素,但显示为:
{
"user": "user1",
"id": "21779"
}
{
"user": "user2",
"id": "21780"
}
它不是有效的json文件。
如何使用json。转储,json。加载或其他方法?谢谢你的帮助!
您必须读取JSON文件,然后将其转换为列表,而不是dict。然后您只需要附加到该列表并覆盖您的JSON文件。
import json
data = json.load(open('data.json'))
# convert data to list if not
if type(data) is dict:
data = [data]
# append new item to data lit
data.append({
"user": "user2",
"id": "21780"
})
# write list to file
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
您可以使用列表而不是判决,如果有帮助,请尝试以下一种解决方案
import json
def appendList():
with open("test.json", mode='r', encoding='utf-8') as f:
feeds = json.load(f)
print(feeds)
with open("test.json", mode='w', encoding='utf-8') as feedsjson:
entry = { "user": "user3","id": "21574"}
feeds.append(entry)
print(json.dump(feeds, feedsjson))