JSON

JSON

chevron-rightmethodshashtag

json (Standard Library for JSON Handling)

pythonCopyEditimport json
Method
Description

json.load()

Parses JSON from file-like object

json.loads()

Parses JSON string

json.dump()

Writes JSON to file-like object

json.dumps()

Converts object to JSON string

json.JSONDecodeError

Exception class for decoding issues

chevron-rightexamplehashtag

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 json module:

import json

🔹 json.load()Load JSON from Config File

import 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

import 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

import 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

import 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.JSONDecodeErrorHandle Malformed JSON from API

import 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)

json.dump(data, f, indent=4)

🔸 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)

print(json.dumps(data, ensure_ascii=False))

🔸 default=str — Serialize datetime or custom objects

import datetime

print(json.dumps({"timestamp": datetime.datetime.utcnow()}, default=str))

✅ Summary Table

Method / Attribute
Description / Use Case

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