How to merge/overwrite two JSON object in Python?
Question:
I want to merge two JSON files while the data overwrites itself in the main JSON file.
My main object is the following:
{
"data": [
{
"name": "name1",
"gender": "male",
"age": "20",
"subject": "Python",
"pass": "No"
}
]
}
"new data.json" needs to be overridden with the following:
{
"data": [
{
"name": "name1",
"subject": "Python",
"pass": "Yes"
}
]
}
The result object should be:
{
"data": [
{
"name": "name1",
"gender": "male",
"age": "20",
"subject": "Python",
"pass": "Yes" //updated
}
]
}
Answers:
In general, you can use the built-in Python update
method for dictionaries, which updates the current dictionary with values of a new one while keeping old data present.
For your case (assuming you always need to update the FIRST element in the array within the "data"
key):
original_data = {
"data": [
{
"name": "name1",
"gender": "male",
"age": "20",
"subject": "Python",
"pass": "No"
}
]
}
new_data = {
"data": [
{
"name": "name1",
"subject": "Python",
"pass": "Yes"
}
]
}
original_data["data"][0].update(new_data["data"][0]) #this updates the original JSON
I want to merge two JSON files while the data overwrites itself in the main JSON file.
My main object is the following:
{
"data": [
{
"name": "name1",
"gender": "male",
"age": "20",
"subject": "Python",
"pass": "No"
}
]
}
"new data.json" needs to be overridden with the following:
{
"data": [
{
"name": "name1",
"subject": "Python",
"pass": "Yes"
}
]
}
The result object should be:
{
"data": [
{
"name": "name1",
"gender": "male",
"age": "20",
"subject": "Python",
"pass": "Yes" //updated
}
]
}
In general, you can use the built-in Python update
method for dictionaries, which updates the current dictionary with values of a new one while keeping old data present.
For your case (assuming you always need to update the FIRST element in the array within the "data"
key):
original_data = {
"data": [
{
"name": "name1",
"gender": "male",
"age": "20",
"subject": "Python",
"pass": "No"
}
]
}
new_data = {
"data": [
{
"name": "name1",
"subject": "Python",
"pass": "Yes"
}
]
}
original_data["data"][0].update(new_data["data"][0]) #this updates the original JSON