[英]Python: append new dictionary to json file
我在下面有一个现有的 json 文件,我想将新字典附加到 json 文件中。
{
"company_id": 1,
"company_name": "Google"
"members": [
{
"name": "John",
"title": "Analyst",
"age": "24",
},
{
"name": "Dave",
"title": "Developer",
"age": "27",
},
{
"name": "Jim",
"title": "Manager",
"age": "34",
}
]
}
我努力了
file_data = json.load(file)
file_data.update(new_data)
file.seek(0)
json.dump(file_data, file, indent=4)
编辑:
新数据如下,字典类型
new_data = {
"company_id": 1,
"company_name": "Google",
"members": [
{
"name": "James",
"title": "CEO",
"age": "50"
}
]
}
它将新数据添加到文件中,但会弄乱现有数据。 这是输出。
{
"company_id": 1,
"company_name": "Google",
"members": [
{
"name": "John",
"title": "Analyst",
"age": "24"
},
{
"name": "Dave",
"title": "Developer",
"age": "27"
},
{
"name": "Jim",
"title": "Manager",
"age": "34"
}
]
}{
"company_id": 1,
"company_name": "Google",
"members": [
{
"name": "James",
"title": "CEO",
"age": "50"
}
]
}
我希望将同一 company_id 中的新成员添加到成员中,但它只是在现有成员之后创建另一个 json。
我认为您需要在转储更新的数据之前关闭 json 文件:
with open("data.json", "r") as f:
data = json.load(f)
data.update(your_data)
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
更新答案
可能您需要直接引用需要添加新数据的位置:
import json
new_data = {
"company_id": 1,
"company_name": "Google",
"members": [
{
"name": "James",
"title": "CEO",
"age": "50"
}
]
}
with open("data1.json", "r") as f:
data = json.load(f)
data['members'] += new_data['members'] # <-- here
with open("data1.json", "w") as f:
json.dump(data, f)
只有当新数据比旧数据长时, file.seek(0)
才能重写打开的文件。 如果新数据更短,你会变得一团糟。
看起来您应该附加新成员:
file_data[‘members’] += new_data[‘members’]
而不是进行更新。
试试这个代码,它对我有用:
your_data = {"d": 4}
with open("file.json", "r+") as file:
data = json.load(file)
data.update(your_data)
file.seek(0)
json.dump(data, file, indent=4)
试试这个
file_data.append(your_data)
假设您仅尝试添加 1,这应该向 json 添加 1 dict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.