Skip to content
Working with JSON
step 1/7

Reading — step 1 of 7

Learn

~2 min readReal-World Python

JSON (JavaScript Object Notation) is the language programs use to talk to each other over the internet. Ask a weather API for today's forecast — it responds in JSON. Send user settings to your backend — it's JSON. Almost every modern API speaks JSON. Python's json module makes it straightforward, once you know the few gotchas.

The four functions you need

python
  • loads / dumps — work with strings (s = string).
  • load / dump — work with file objects.

How types translate

JSONPython
objectdict
arraylist
stringstr
numberint or float
true / falseTrue / False
nullNone

Not all Python types map cleanly to JSON. Tuples become lists. Sets are NOT serializable. Datetimes need conversion.

Pretty-printing

python

Indent of 2 or 4 produces human-readable output. Without indent, you get a compact one-line form.

Sorting keys for consistent output

python

Useful for diffing JSON files or hashing.

Handling missing keys safely

python

JSON parsed into a dict — same .get() rules apply as any dict.

Catching parse errors

python

Real-world JSON (from APIs, user input) often has issues — always wrap in try/except for robustness.

Serializing custom objects

Stock json.dumps doesn't know about your classes:

python

Provide a default function:

python

For dataclasses, dataclasses.asdict() converts to a dict in one line.

json.dumps options summary

python

Common mistakes

  • Confusing loads and load (string vs file). s at the end = string.
  • Trying to JSON-serialize sets, datetimes, or custom objects without a default function.
  • Single quotes — JSON requires DOUBLE quotes for strings. '{"a": 1}' is valid JSON; "{'a': 1}" is not.
  • Trailing commas — JSON spec forbids them: {"a": 1,} is invalid (Python dicts allow them).
  • Comments — JSON spec doesn't allow comments (use JSONC if you need them).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…