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.
More on Data formats, HTTP & REST APIs
Why must you use `yaml.safe_load` rather than `yaml.load`?BeginnerHow do you load a multi-document Kubernetes YAML file?IntermediateHow do you read and write CSV files properly?BeginnerHow do you make an HTTP request with `requests` the right way?BeginnerWhy use a `requests.Session`?IntermediateHow do you add retries with exponential backoff to `requests`?Intermediate