Skip to content

Instantly share code, notes, and snippets.

@thejoshwolfe
Created January 25, 2013 05:08
Show Gist options
  • Save thejoshwolfe/4631935 to your computer and use it in GitHub Desktop.
Save thejoshwolfe/4631935 to your computer and use it in GitHub Desktop.
json object diff
#!/usr/bin/env python
import sys
import json
def diff_objects(left, right):
if not (type(left) == type(right) == dict):
return right
result = {}
keys = set()
keys.update(left.keys())
keys.update(right.keys())
for key in keys:
left_child, right_child = left.get(key, None), right.get(key, None)
if left_child != right_child:
result[key] = diff_objects(left_child, right_child)
return result
def apply_diff(obj, diff):
for key, child_diff in diff.items():
child = obj.get(key, None)
if child_diff == None:
del obj[key]
elif not (type(child) == type(child_diff) == dict):
obj[key] = child_diff
else:
apply_diff(child, child_diff)
if __name__ == "__main__":
(left_path, right_path) = sys.argv[1:]
def load(path):
with open(path) as f:
return json.load(f)
left, right = load(left_path), load(right_path)
diff = diff_objects(left, right)
sys.stdout.write(json.dumps(diff, indent=2, sort_keys=True))
sys.stdout.write("\n")
apply_diff(left, diff)
assert(left == right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment