首页 > 解决方案 > how to compare to two json files and return a un matched key and value in object

问题描述

JSON File1:

 [{
    "App_Name": "Test1",
    "Instances": "2",
    "Memory": "2G",
    "Disk_Quota": "1G"
}, {
    "App_Name": "Test2",
    "Instances": "2",
    "Memory": "2G",
    "Disk_Quota": "1G"
}, {
    "App_Name": "Test3",
    "Instances": "1",
    "Memory": "1G",
    "Disk_Quota": "1G"
}]

JSON file2:

 [ {
    "App_Name": "Test3",
    "Instances": "1",
    "Memory": "1G",
    "Disk_Quota": "5G"
 },{
    "App_Name": "Test1",
    "Instances": "3",
    "Memory": "2G",
    "Disk_Quota": "1G"
}, {
    "App_Name": "Test2",
    "Instances": "2",
    "Memory": "8G",
    "Disk_Quota": "1G"
}]

I have to compare both the JSON files and need to print the unmatched value from the JSON objects.

So far I have tried this one

def Compare():

    with open("Jsonfile1.json") as f:
        data = f.read()
        env1 = json.loads(data)

    with open("jsonfile2.json") as f:
        data = f.read()
        env2 = json.loads(data)



    for name in env1:
            for names in env2:
                if name['App_Name'] == names['App_Name']:
                    if name['Instances'] != names['Instances']:
                        print("unmatched val {} -i {}".format(name['App_Name'],names['Instances']))
                        if name['Memory'] != names['Memory']:
                            # print(name['Memory'], names['Memory'])
                            print("unmatched val {} -m {}".format(name['App_Name'],names['Memory']))
                            if name['Disk_Quota'] != names['Disk_Quota']:
                                print("unmatched val {} -k {}".format(name['App_Name'],names['Disk_Quota']))

Compare()

Excepted output :

if there is a mismatch in instance then print(jsonfile1 instance value) if there is a mismatch in memory then print(jsonfile1 memory value) if there is a mismatch in disk then print(jsonfile1 disk value)

标签: python-3.x

解决方案


这应该做的工作:

for d1 in env1:  # Iterate over all dictionaries in first JSON
    # Look for the corresponding dictionary in second JSON
    candidates = [d for d in env2 if d["App_Name"] == d1["App_Name"]]
    if not candidates:
        print(d1)  # If no corresponding dict, just print and go to next
    else:
        d2 = candidates[0]  # If corresponding dict, look for mismatches
        for key in d1:
            if d1.get(key) != d2.get(key):  # Find mismatches
                print(f"mismatch detected for app='{d1['App_Name']}'")
                print(f"\tenv1's value for key='{key}' is {d1.get(key)}")
                print(f"\twhile env2's value for key='{key}' is {d2.get(key)}")

输出:

mismatch detected for app='Test1'
    env1's value for key='Instances' is 2
    while env2's value for key='Instances' is 3
mismatch detected for app='Test2'
    env1's value for key='Memory' is 2G
    while env2's value for key='Memory' is 8G
mismatch detected for app='Test3'
    env1's value for key='Disk_Quota' is 1G
    while env2's value for key='Disk_Quota' is 5G

推荐阅读