Search code examples
pythonjsonfilecomparison

Compare two JSON Files and Return the Difference


I have found some similar questions to this. The problem is that none of those solutions work for me and some are too advanced. I'm trying to read the two JSON files and return the difference between them.

I want to be able to return the missing object from file2 and write it into file1.

These are both the JSON files

file1

[
 {
    "name": "John Wood",
    "age": 35,
    "country": "USA"
 },
 {
    "name": "Mark Smith",
    "age": 30,
    "country": "USA"
 }
]

.

file2

[
 {
    "name": "John Wood",
    "age": 35,
    "country": "USA"
 },
 {
    "name": "Mark Smith",
    "age": 30,
    "country": "USA"
 },
 {
    "name": "Oscar Bernard",
    "age": 25,
    "country": "Australia"
 }
]

The code

with open("file1.json", "r") as f1:
    file1 = f1.read()
    item1 = json.loads(file1)
    print(item1)

with open("file2.json", "r") as f2:
    file2 = f2.read()
    item2 = json.loads(file2)
    print(item2)

# Returns if that index is the same
for v in range(len(item1)):
    for m in range(len(item2)):
        if item2[v]["name"] == item1[m]["name"]:
            print("Equal")
        else:
            print("Not Equal")

I'm not used to programming using JSON or comparing two different files. I would like help to return the difference and basically copy and paste the missing object into file1. What I have here shows me if each object in file1 is equal or not to file2. Thus, returning the "Equal" and "Not Equal" output.

Output:

Equal
Not Equal
Not Equal
Not Equal
Equal
Not Equal

I want to return if file1 is not equal to file2 and which object ("name") is the one missing. Afterward, I want to be able to add/copy that missing object into file2 using with open("file2.json", "w").


Solution

  • with open("file1.json", "r") as f1:
        file1 = json.loads(f1.read())
    with open("file2.json", "r") as f2:
        file2 = json.loads(f2.read())
    
    for item in file2:
        if item not in file1:
            print(f"Found difference: {item}")
            file1.append(item)
    
    print(f"New file1: {file1}")