TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Parsing JSON and YAML in Python

Parsing JSON and YAML in Python

Once data is in Python dictionaries and lists, everything is easy. The work is at the edges: decoding JSON that is not quite what you expected, reading multi-document YAML, writing YAML that other tools read back the same way, and not losing comments when you edit a file a human maintains. The examples use the standard json module and PyYAML 6.0, the YAML library most tools depend on.

JSON: load, dump and the types that do not fit

python · try it yourself
import json
from datetime import datetime, timezone
from decimal import Decimal

raw = '{"service": "shop-api", "replicas": 3, "ratio": 0.75, "tags": ["a", "b"], "owner": null, "public": true}'
doc = json.loads(raw)
print(doc)
print(type(doc["replicas"]).__name__, type(doc["ratio"]).__name__, doc["owner"] is None)

# Pretty, stable output: sorted keys make diffs and checksums reproducible
print(json.dumps(doc, indent=2, sort_keys=True))

# Types JSON does not have
event = {"at": datetime(2026, 1, 15, 10, 0, tzinfo=timezone.utc), "cost": Decimal("12.40"), "hosts": {"web-1"}}
try:
    json.dumps(event)
except TypeError as e:
    print("TypeError:", e)

def encode(o):
    if isinstance(o, datetime):
        return o.isoformat().replace("+00:00", "Z")
    if isinstance(o, Decimal):
        return str(o)                  # keep the exact value as a string
    if isinstance(o, set):
        return sorted(o)
    raise TypeError(f"cannot encode {type(o).__name__}")

print(json.dumps(event, default=encode))

# Bad input: the error says where
try:
    json.loads('{"replicas": 3,}')
except json.JSONDecodeError as e:
    print(f"invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}")
{'service': 'shop-api', 'replicas': 3, 'ratio': 0.75, 'tags': ['a', 'b'], 'owner': None, 'public': True}
int float True
{
  "owner": null,
  "public": true,
  "ratio": 0.75,
  "replicas": 3,
  "service": "shop-api",
  "tags": [
    "a",
    "b"
  ]
}
TypeError: Object of type datetime is not JSON serializable
{"at": "2026-01-15T10:00:00Z", "cost": "12.40", "hosts": ["web-1"]}
invalid JSON at line 1, column 15: Illegal trailing comma before end of object
  • sort_keys=True makes the output deterministic, which matters for anything you commit, compare or hash.
  • default= handles the types JSON lacks. Dates as ISO 8601 strings in UTC are the convention for APIs and logs.
  • json.JSONDecodeError carries the line and column: put them in your error message.

Reading data defensively

API responses and config files have optional fields. dict.get with a default, and a small helper for nested paths, keep KeyErrors out of your scripts without hiding real problems:

python · try it yourself
import json

pods = json.loads("""{"items": [
  {"metadata": {"name": "api-7d9f", "labels": {"app": "api"}}, "status": {"phase": "Running",
   "containerStatuses": [{"ready": true, "restartCount": 0}]}},
  {"metadata": {"name": "migrate-q8z1"}, "status": {"phase": "Pending"}}
]}""")

def dig(obj, *path, default=None):
    """Follow keys/indexes; return default if any step is missing (like jq's `.a.b // default`)."""
    for key in path:
        try:
            obj = obj[key]
        except (KeyError, IndexError, TypeError):
            return default
    return obj

for pod in pods["items"]:                      # "items" is required: let a KeyError surface
    name = pod["metadata"]["name"]
    app = dig(pod, "metadata", "labels", "app", default="-")
    ready = all(c.get("ready", False) for c in dig(pod, "status", "containerStatuses", default=[]))
    restarts = sum(c.get("restartCount", 0) for c in dig(pod, "status", "containerStatuses", default=[]))
    print(f"{name:14} app={app:4} ready={ready!s:5} restarts={restarts}")
api-7d9f       app=api  ready=True  restarts=0
migrate-q8z1   app=-    ready=True  restarts=0

Decide per field: required fields are read with [] so a missing one fails loudly; optional ones get a default. Note that all([]) is True: the pending pod with no containers counts as "ready" here, which is exactly the kind of edge case to decide on purpose.

YAML: safe_load, multiple documents, dumping

python · try it yourself
import yaml

text = """
apiVersion: apps/v1
kind: Deployment
metadata: {name: shop-api}
spec: {replicas: 2}
---
apiVersion: v1
kind: Service
metadata: {name: shop-api}
spec:
  ports: [{port: 80, targetPort: 8080}]
"""
docs = list(yaml.safe_load_all(text))           # one dict per --- document
print([f"{d['kind']}/{d['metadata']['name']}" for d in docs])

deploy = next(d for d in docs if d["kind"] == "Deployment")
deploy["spec"]["replicas"] = 4
deploy["metadata"]["labels"] = {"app": "shop-api", "version": "1.10"}

out = yaml.safe_dump_all(docs, sort_keys=False, default_flow_style=False)
print(out, end="")
print("round trip equal:", list(yaml.safe_load_all(out)) == docs)
['Deployment/shop-api', 'Service/shop-api']
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
  labels:
    app: shop-api
    version: '1.10'
spec:
  replicas: 4
---
apiVersion: v1
kind: Service
metadata:
  name: shop-api
spec:
  ports:
  - port: 80
    targetPort: 8080
round trip equal: True
  • safe_load / safe_load_all only build plain Python types (never yaml.load on untrusted input; see YAML Gotchas).
  • sort_keys=False keeps the familiar apiVersion, kind, metadata, spec order; PyYAML sorts keys by default.
  • PyYAML quotes the string '1.10' when dumping, because unquoted it would read back as a float. The dumper knows the 1.1 rules and protects strings like 'NO', 'on' and '0755' the same way.

The comment problem

PyYAML drops comments and reformats the file. That is fine for files a program owns (generated manifests) and bad for files people maintain (Helm values, CI configs). Options:

Need Use
change one value in a human-maintained file yq -i from the shell (yq)
programmatic edits that keep comments and order in Python ruamel.yaml (round-trip mode), a third-party package
generate a file nobody edits by hand PyYAML safe_dump, or write JSON (valid YAML too)
python
# ruamel.yaml keeps comments, key order and quoting (not available in this browser sandbox)
from ruamel.yaml import YAML

yaml = YAML()                         # round-trip mode by default
with open("values.yaml") as f:
    values = yaml.load(f)
values["image"]["tag"] = "1.5.0"
with open("values.yaml", "w") as f:
    yaml.dump(values, f)

Test yourself

Why pass sort_keys=True to json.dumps for files you commit or hash?

  1. It makes the output smaller
  2. The output becomes deterministic, so diffs and checksums only change when the data does
  3. JSON requires sorted keys
  4. It validates the data

Which PyYAML function reads every --- document in a file?

  1. yaml.safe_load
  2. yaml.safe_load_all
  3. yaml.load
  4. yaml.compose

What happens to comments when you load and dump a file with PyYAML?

  1. They are kept
  2. They are lost; use yq -i or ruamel.yaml when comments matter
  3. They become keys
  4. PyYAML refuses files with comments