Created
November 28, 2012 17:00
-
-
Save xuru/4162537 to your computer and use it in GitHub Desktop.
Determines if two python objects differ (only json types supported)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def json_diff(obj, other, order_matters=True): | |
| """ This method assumes json types: dict, list, strings, numbers, booleans and null """ | |
| if isinstance(obj, dict) and isinstance(other, dict): | |
| if set(obj.keys()) != set(other.keys()): | |
| return True | |
| for key in sorted(obj.keys()): | |
| if json_diff(obj[key], other[key], order_matters): | |
| return True | |
| elif isinstance(obj, list) and isinstance(other, list): | |
| if len(obj) != len(other): | |
| return True | |
| if not order_matters: | |
| obj_dict = {} | |
| for x in obj: | |
| if x.__class__.__name__ not in obj_dict.keys(): | |
| obj_dict[x.__class__.__name__] = [x] | |
| else: | |
| obj_dict[x.__class__.__name__].append(x) | |
| other_dict = {} | |
| for x in other: | |
| if x.__class__.__name__ not in other_dict.keys(): | |
| other_dict[x.__class__.__name__] = [x] | |
| else: | |
| other_dict[x.__class__.__name__].append(x) | |
| for k in obj_dict.keys(): | |
| obj_dict[k].sort() | |
| for k in other_dict.keys(): | |
| other_dict[k].sort() | |
| _one = [] | |
| for x in obj_dict.values(): | |
| _one += x | |
| _two = [] | |
| for x in other_dict.values(): | |
| _two += x | |
| obj = _one | |
| other = _two | |
| for v1, v2 in zip(obj, other): | |
| if json_diff(v1, v2, order_matters): | |
| return True | |
| elif obj != other: | |
| return True | |
| return False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment