I have an existing json file below and I want to append new dictionary to the json file.
{
"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",
}
]
}
I have tried
file_data = json.load(file)
file_data.update(new_data)
file.seek(0)
json.dump(file_data, file, indent=4)
EDITED:
New data is as below with dict type
new_data = {
"company_id": 1,
"company_name": "Google",
"members": [
{
"name": "James",
"title": "CEO",
"age": "50"
}
]
}
It adds the new data to the file but messes up the existing data. Here is the output.
{
"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"
}
]
}
I want it the new member in the same company_id to be added within the members but it just creates another json after the exisiting one.
I think you need to close the json file before you dump the updated datа:
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)
Updated answer
Probably you need to refer directly where you need to add the new data:
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)
The file.seek(0)
to rewrite an opened file works only if the new data is longer that old one. If the new data is shorter you will get the mess.
It just looks like you should append the new members:
file_data[‘members’] += new_data[‘members’]
instead of doing an update.
Try this code, it works for me:
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)
try this
file_data.append(your_data)
this should add 1 dict to the json assuming you are trying to add just 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.