Last active
January 8, 2019 20:32
-
-
Save josh-hernandez-exe/815188debf2fce1fc0c8518b6a92757c to your computer and use it in GitHub Desktop.
Test if two json dicts are equal.
This file contains 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 _get_json_iterator(json): | |
if isinstance(json, dict): | |
return json.keys() | |
elif isinstance(json, list): | |
return range(len(json)) | |
else: | |
raise Exception() | |
def is_json_equal(json_a, json_b): | |
if json_a is json_b: | |
return True | |
if json_a is None or json_b is None: | |
return False | |
b_contains_a = False | |
for key in _get_json_iterator(json_a): | |
if key not in json_b: | |
break | |
value_a = json_a[key] | |
value_b = json_b[key] | |
if type(value_a) is not type(value_b): | |
break | |
if isinstance(value_a, (dict, list)) and not is_json_equal(value_a, value_b): | |
break | |
elif value_a != value_b: | |
break | |
else: | |
# only executes if break is not executed | |
b_contains_a = True | |
# we recurrsivly checked if all keys in json_a are in json_b | |
# as well as recurrsivly check the values of those keys. | |
# we need to check that json_b doesn't have extra keys | |
a_contains_b = False | |
if b_contains_a: # be lazy | |
for key in _get_json_iterator(json_b): | |
if key not in json_a: | |
break | |
else: | |
# only executes if break is not executed | |
a_contains_b = True | |
return b_contains_a and a_contains_b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment