JSON
JSON
example
Here’s a DevOps/SRE-focused guide with real-world examples for each method and attribute of Python’s built-in json module — including missing but commonly used parameters and use cases.
✅ JSON (Python Standard Library)
First, ensure you're using the built-in
jsonmodule:
import json🔹 json.load() — Load JSON from Config File
json.load() — Load JSON from Config Fileimport json
with open("config.json") as f:
config = json.load(f)
print("Environment:", config["env"])✅ Use when reading a JSON file such as Terraform variable definitions or app config.
🔹 json.loads() — Parse API Response String
json.loads() — Parse API Response Stringimport json
response = '{"status": "ok", "region": "us-west-2"}'
data = json.loads(response)
print("Region:", data["region"])✅ Converts string from shell/API/HTTP into a Python dict.
🔹 json.dump() — Write Monitoring Output to File
json.dump() — Write Monitoring Output to Fileimport json
status = {"uptime": "99.9%", "services": 5}
with open("status.json", "w") as f:
json.dump(status, f, indent=2)
print("Status report written")✅ Use indent=2 for readable formatting.
🔹 json.dumps() — Serialize Object for HTTP POST
json.dumps() — Serialize Object for HTTP POSTimport json
import requests
payload = {"job": "backup", "status": "started"}
json_payload = json.dumps(payload)
response = requests.post("https://api.internal/jobs", data=json_payload)
print("Job submitted")✅ Converts Python dict to JSON string for webhooks/APIs.
🔹 json.JSONDecodeError — Handle Malformed JSON from API
json.JSONDecodeError — Handle Malformed JSON from APIimport json
try:
json.loads("{invalid json}")
except json.JSONDecodeError as e:
print("JSON decode error:", e)✅ Useful in automation to gracefully handle errors.
🔹 Commonly Missed Attributes and Parameters
🔸 indent — Pretty-print JSON (for logs/config)
indent — Pretty-print JSON (for logs/config)json.dump(data, f, indent=4)🔸 sort_keys=True — Sort output by keys (useful for diffs)
sort_keys=True — Sort output by keys (useful for diffs)print(json.dumps(data, indent=2, sort_keys=True))🔸 ensure_ascii=False — Preserve UTF-8 (for non-English text)
ensure_ascii=False — Preserve UTF-8 (for non-English text)print(json.dumps(data, ensure_ascii=False))🔸 default=str — Serialize datetime or custom objects
default=str — Serialize datetime or custom objectsimport datetime
print(json.dumps({"timestamp": datetime.datetime.utcnow()}, default=str))✅ Summary Table
json.load()
Load JSON from file (e.g., config.json, Terraform plan output)
json.loads()
Parse JSON string (e.g., from API or shell command)
json.dump()
Write dict to file as JSON (e.g., log monitoring results)
json.dumps()
Convert dict to JSON string (e.g., for HTTP POST)
json.JSONDecodeError
Catch and handle bad JSON from sources like APIs or logs
indent
Format output nicely for readability (logs, configs)
sort_keys=True
Alphabetical keys (helpful in version control diffs)
ensure_ascii=False
Keep non-English characters readable
default=str
Serialize custom types like datetime or UUID
Would you like:
📘 A PDF cheat sheet
📊 A chart image version
🧪 A Jupyter Notebook version with outputs
📦 Or a combined DevOps JSON+YAML+boto3+requests guide?
Last updated