所以我有一个基本的user.json
文件。
我的问题是:如何向我的JSON列表中添加另一个字典?
所以下面有我的代码,如您所见,我尝试了此操作:append
,update
,insert
,但找不到任何工作结果。目标是能够添加一个新的:
NAME:name1 //国家/地区:coutry1 //性别:gender1 ...到人员JSON列表...。谢谢。Python代码
import json
with open("user.json") as f:
data = json.load(f)
new_dict = {"name": "name1",
"Country": "Country2",
"Gender": "Gender3"}
for person in data["person"]:
person.update(new_dict)
with open("user.json", "w") as f:
json.dump(data, f, indent=2)
user.json
{
"person": [
{
"name": "Peter",
"Country": "Montreal",
"Gender": "Male"
},
{
"name": "Alex",
"Country": "Laval",
"Gender": "Male"
},
{
"name": "Annie",
"Country": "Quebec",
"Gender": "Female"
},
{
"name": "Denise",
"Country": "Levis",
"Gender": "Female"
}
]
}
如果要向人员列表添加另一个人员对象,您要做的就是将新对象附加到对象数组中。您无需遍历人员对象。请检查下面的代码是否对您有帮助:
with open("user.json") as f:
data = json.load(f)
new_dict = {"name": "name1",
"Country": "Country2",
"Gender": "Gender3"}
data["person"].append(new_dict)
with open("user.json", "w") as f:
json.dump(data, f, indent=2)
在person.update(new_dict)
处的python代码中,您正在更改已经存在的条目person
,不会添加新条目。