Created
September 3, 2009 10:22
-
-
Save simonw/180228 to your computer and use it in GitHub Desktop.
Returns a list of differences between two JSON objects - useful for smarter unit test error messages
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_diffs(a, b, path='_'): | |
| errors = [] | |
| if type(a) != type(b): | |
| return ['%s: Type of a (%s) != type of b (%s)' % (path, type(a), type(b))] | |
| if type(a) == dict: | |
| for key in a: | |
| new_path = path + ('[%s]' % key) | |
| if key not in b: | |
| errors.append('%s: Key %s present in a but not in b' % (new_path, key)) | |
| else: | |
| errors.extend(json_diffs(a[key], b[key], new_path)) | |
| for key in b: | |
| new_path = path + ('[%s]' % key) | |
| if key not in a: | |
| errors.append('%s: Key %s present in b but not in a' % (new_path, key)) | |
| elif type(a) == list: | |
| if len(a) != len(b): | |
| errors.append('%s: len(a) (%s) != len(b) (%s)' % (path, len(a), len(b))) | |
| for i, item in enumerate(a): | |
| errors.extend(json_diffs(item, b[i], path=path + '[%s]' % i)) | |
| else: | |
| if a != b: | |
| errors.append('%s: a != b (%r != %r)' % (path, a, b)) | |
| return errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment