Mia
Mia

Reputation: 448

Compare two nested json files and show user where exactly the change has occurred and which json file using Python?

I have two json files. I am validating the response is same or different. I need to show the user where there is an exact change. Some what like the particular key is added or removed or changed in this file.

file1.json

[
{
  "Name": "Jack",
  "region": "USA",
  "tags": [
     {
        "name": "Name",
        "value": "Assistant"
     }
   ]
 },
  {
  "Name": "MATHEW",
  "region": "USA",
  "tags": [
     {
        "name": "Name",
        "value": "Worker"
      }
   ]
  }
]

file2.json

    [
{
  "Name": "Jack",
  "region": "USA",
  "tags": [
     {
        "name": "Name",
        "value": "Manager"
     }
   ]
 },
  {
  "Name": "MATHEW",
  "region": "US",
  "tags": [
     {
        "name": "Name",
        "value": "Assistant"
      }
   ]
  }
 ]

If you see Two JSON you can find the difference as a region in file2.json has changed US and Values changed from manager to assistant and worker. Now I want to show the user that file2.json has some changes like region :US and Manager changed to Assistant.

I have used deepdiff for validating purpose.

from deepdiff import DeepDiff

def difference(oldurl_resp,newurl_resp,file1):
    ddiff = DeepDiff(oldurl_resp, newurl_resp,ignore_order=True)

     if(ddiff == {}):

        print("BOTH JSON FILES MATCH !!!")
        return True

    else:
       print("FAILURE")

       output = ddiff
       if(output.keys().__contains__('iterable_item_added')):
         test = output.get('iterable_item_added')
         print('The Resource name are->')
         i=[]
         for k in test:
            print("Name: ",test[k]['Name'])
            print("Region: ",test[k]['region'])
            msg= (" Name ->"+ test[k]['Name'] +" Region:"+test[k]['region'] +".  ")

            i.append(msg)


           raise JsonCompareError("The json file has KEYS changed!. Please validate  for below" +str(i) +"in "+file1)

    elif(output.keys().__contains__('iterable_item_removed')):
        test2 = output.get('iterable_item_removed')
        print('The name are->')
        i=[]
        for k in test2:
            print(test2[k]['Name'])
            print(test2[k]['region'])
            msg= (" Resource Name ->"+ test2[k]['Name'] +" Region:"+test2[k]['region'] +".  ")

            i.append(msg)


        raise JsonCompareError("The json file has Keys Removed!!. Please validate for below" +str(i)+"in "+file1)

This code just shows the resource Name I want to show the tags also which got changed and added or removed. Can anybody guide me

Upvotes: 0

Views: 1785

Answers (2)

sunny
sunny

Reputation: 748

You should try the deepdiff library. It gives you the key where the difference occurs and the old and new value.

from deepdiff import DeepDiff
ddiff = DeepDiff(json_object1, json_object2)

# if you want to compare by ignoring order
ddiff = DeepDiff(json_object1, json_object2, ignore_order=True)

Upvotes: 2

MohammadMahdi Eilbeigi
MohammadMahdi Eilbeigi

Reputation: 316

If you just print out the values of "test" variables, you will find out that "tag" variable changes are inside of it, test value of test in this example will be:

test = {'root[0]': {'region': 'USA', 'Name': 'Jack', 'tags': [{'name': 'Name', 'value': 'Manager'}]}, 'root[1]': {'region': 'US', 'Name': 'MATHEW', 'tags': [{'name': 'Name', 'value': 'Assistant'}]}}

and you can print test[k]['tags'] or add it your "msg" variable.

Suggestion:

Also, if your data has some primary key (for example they have "id", or their order is always fixed), you can compare their data 1 by 1 (instead of comparing whole lists) and you can have a better comparison. For example if you compare data of "Jack" together, you will have the following comparison:

{'iterable_item_removed': {"root['tags'][0]": {'name': 'Name', 'value': 'Assistant'}}, 'iterable_item_added': {"root['tags'][0]": {'name': 'Name', 'value': 'Manager'}}}

Upvotes: 1

Related Questions