How to compare 2 json in python

How to compare 2 json objects in python below - json sample.

sample_json1={ { "globalControlId": 72, "value": 0, "controlId": 2 }, { "globalControlId": 77, "value": 3, "controlId": 7 } } sample_json2={ { "globalControlId": 72, "value": 0, "controlId": 2 }, { "globalControlId": 77, "value": 3, "controlId": 7 } } 
+12
python
Jun 21 '12 at 15:34
source share
2 answers

Normal comparison seems to work fine

 import json x = json.loads("""[ { "globalControlId": 72, "value": 0, "controlId": 2 }, { "globalControlId": 77, "value": 3, "controlId": 7 } ]""") y = json.loads("""[{"value": 0, "globalControlId": 72,"controlId": 2}, {"globalControlId": 77, "value": 3, "controlId": 7 }]""") x == y # result: True 
+11
Jun 21 '12 at 15:43
source share

these are invalid JSON / Python objects since array / list literals are inside [] instead of {} :

UPDATE : to compare a list of dictionaries (a serialized array of JSON objects), ignoring the order of the list items, the lists must be sorted or converted to settings

 sample_json1=[{"globalControlId": 72, "value": 0, "controlId": 2}, {"globalControlId": 77, "value": 3, "controlId": 7}] sample_json2=[{"globalControlId": 77, "value": 3, "controlId": 7}, {"globalControlId": 77, "value": 3, "controlId": 7}, # duplicity {"globalControlId": 72, "value": 0, "controlId": 2}] # dictionaries are unhashable, let convert to strings for sorting sorted_1 = sorted([repr(x) for x in sample_json1]) sorted_2 = sorted([repr(x) for x in sample_json2]) print(sorted_1 == sorted_2) # in case the dictionaries are all unique or you don't care about duplicities, # sets should be faster than sorting set_1 = set(repr(x) for x in sample_json1) set_2 = set(repr(x) for x in sample_json2) print(set_1 == set_2) 
+3
Jun 21 2018-12-18T00:
source share



All Articles