I have 2 files like these:
file1.json
[
{
"name": "john",
"version": "0.0"
},
{
"name": "peter",
"version": "1.0"
},
{
"name": "bob",
"version": "2.0",
"single": "true"
}
]
file2.json
[
{
"name": "jane",
"version": "0.0"
},
{
"name": "peter",
"version": "1.0"
},
{
"name": "bob",
"version": "2.0",
"single": "true"
}
]
I want to compare the "name" values in file1.json with the "name" values in file2.json. If file2.json has some "name" values not in file1.json, I want to append that json object to file1.json.
For the above 2 files, I want file1 to be appended with the "name": "jane" object since that is not present in file1. So file1 should be updated to:
[
{
"name": "john",
"version": "0.0"
},
{
"name": "peter",
"version": "1.0"
},
{
"name": "bob",
"version": "2.0",
"single": "true"
},
{
"name": "jane",
"version": "0.0"
}
]
What I have tried:
with open('file1.json', 'r') as file1, open('file2.json', 'r') as file2:
file1_json = json.load(file1)
file2_json = json.load(file2)
for object in file2_json:
if object['name'] not in file1_json.values():
file1_json.update(object)
with open('file1.json', 'w') as file1:
json.dump(file1_json, file1, indent=4)
4
Answers
Collect the names in
file1_json
, find the missing names infile2_json
, then add them tofile1_json
:Output:
This should work if all dictionary values are immutable (which they are):
You could create an index into json2 to speed lookups. Then take the set of names from each and subtract. The result is the missing names. Use the index to add the missing values.
I believe what you want is to merge dictionaries essentially. The fact it comes from a json does not really matter here.
Take a look at this.
https://stackoverflow.com/a/62820532/4944708
Here’s the full solution, assuming you have read the jsons in: