Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two JSON objects irrespective of the sequence of elements in them

Tags:

python

json

Is there any way / class / module in python to compare two json objects and print the changes/differences?

I have tried with "json_tools" which is gives fairly good results, however diff failed in case if there are python lists' with elements in different orders in two json objects.

e.g.

JSON 1:

{
    'Person' : 
        {
            'FName'    : 'John',
            'LName'    : 'Rambo',
            'Sex'      : 'Male'
            'Height'   : '6 ft',
            'Weight'   : '90 KG',
            'Children' :
                [
                    {
                        'FName'  : 'Anna',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Female',
                        'Height' : '5 ft',
                        'Weight' : '55 KG',
                    },
                    {
                        'FName'  : 'Jemmy',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Male',
                        'Height' : '5 ft',
                        'Weight' : '60 KG',
                    }

                ]
        }
}

JSON 2:

{
    'Person' : 
        {
            'FName'    : 'John',
            'LName'    : 'Rambo',
            'Sex'      : 'Male'
            'Height'   : '6 ft',
            'Weight'   : '90 KG',
            'Children' :
                [
                    {
                        'FName'  : 'Jemmy',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Male',
                        'Height' : '5 ft',
                        'Weight' : '60 KG',
                    },
                    {
                        'FName'  : 'Anna',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Female',
                        'Height' : '5 ft',
                        'Weight' : '55 KG',
                    }
                ]
        }
}

json diff shows the Two jsons are mismatched.. Logically those are identical..

Is there a good way of json matching and comparing in python?

like image 313
Abhishek Kulkarni Avatar asked Jul 12 '13 04:07

Abhishek Kulkarni


2 Answers

You can use jsondiff

from jsondiff import diff
diff(json1, json2)

... assuming you have json1 and json2 loaded with the json entries from your example (and by the way, you have a missing comma after the 'sex' entry).

like image 103
user2111922 Avatar answered Oct 20 '22 22:10

user2111922


you can use deepdiff with ignore_order=True

from deepdiff import DeepDiff
t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
ddiff = DeepDiff(t1, t2, ignore_order=True)
print (ddiff)
{}
like image 30
Nir Soudry Avatar answered Oct 21 '22 00:10

Nir Soudry