Compare two JSON files and print keys that differ.
IntermediateHands-onPython for DevOps
Answer
import json
import sys
def diff(a, b, path=""):
for k in sorted(set(a) | set(b)):
p = f"{path}.{k}" if path else k
if k not in a: print(f"+ {p} = {b[k]!r}")
elif k not in b: print(f"- {p} = {a[k]!r}")
elif isinstance(a[k], dict) and isinstance(b[k], dict):
diff(a[k], b[k], p)
elif a[k] != b[k]:
print(f"~ {p}: {a[k]!r} -> {b[k]!r}")
with open(sys.argv[1]) as f1, open(sys.argv[2]) as f2:
diff(json.load(f1), json.load(f2))
Key trick → Use the union of key sets to find additions and removals, and recurse only when both sides are dicts.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate