Reading — step 1 of 7
Learn
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
loads/dumps— work with strings (s = string).load/dump— work with file objects.
How types translate
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number | int or float |
| true / false | True / False |
| null | None |
Not all Python types map cleanly to JSON. Tuples become lists. Sets are NOT serializable. Datetimes need conversion.
Pretty-printing
Indent of 2 or 4 produces human-readable output. Without indent, you get a compact one-line form.
Sorting keys for consistent output
Useful for diffing JSON files or hashing.
Handling missing keys safely
JSON parsed into a dict — same .get() rules apply as any dict.
Catching parse errors
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:
Provide a default function:
For dataclasses, dataclasses.asdict() converts to a dict in one line.
json.dumps options summary
Common mistakes
- Confusing
loadsandload(string vs file).sat the end = string. - Trying to JSON-serialize sets, datetimes, or custom objects without a
defaultfunction. - 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…