Interview Prep/Python for DevOps/Data formats, HTTP & REST APIs

How do you read and write JSON, and what are the common gotchas?

BeginnerConceptData formats, HTTP & REST APIs
Answer
import json
data = json.loads(text)                      # str -> obj
with open("state.json", encoding="utf-8") as f:
    data = json.load(f)                      # file -> obj
json.dumps(data, indent=2, sort_keys=True, default=str)

Gotchas: datetime, Decimal and set are not serializable (TypeError: Object of type datetime is not JSON serializable; pass default=str or a custom function). JSON keys are always strings, so {1: "a"} round-trips as {"1": "a"}. json.load reads the whole file; for huge files use JSON Lines.

All Python for DevOps questions Roadmap: Python for automation

More on Data formats, HTTP & REST APIs