Module 13 · File Handling — topic 11 of 15
JSON files
Storing structured data with the json module: dump and load for files, dumps and loads for strings, how Python types map to JSON, pretty-printing, non-ASCII text and handling invalid JSON.
Learning objectives
- Save and load data with json.dump and json.load
- Know how Python types map to JSON
- Handle invalid JSON and missing files
Definition
JSON (JavaScript Object Notation) is a text format for structured data made of objects, arrays, strings, numbers, booleans and null. The json module converts between JSON text and Python dictionaries, lists and values.
Introduction
Settings, saved games and web API responses are usually JSON. It maps naturally onto Python dictionaries and lists, so saving structured data takes one line.
Why it matters
JSON is the lingua franca of the web and of configuration files. Being able to read and write it is essential for real projects.
Detailed explanation
json.dump(obj, f) writes obj to an open file; json.load(f) reads it back. dumps and loads (with an s for 'string') work with strings instead.
Type mapping: dict ↔ object, list/tuple → array, str ↔ string, int/float ↔ number, True/False ↔ true/false, None ↔ null. Tuples come back as lists.
JSON object keys are always strings; integer keys become strings when saved.
indent=2 produces readable, indented output; sort_keys=True orders keys; ensure_ascii=False keeps non-English characters readable instead of \u escapes.
Only basic types are supported. Sets, dates and custom objects raise TypeError unless you convert them (for example to lists or ISO date strings).
Invalid JSON raises json.JSONDecodeError (a subclass of ValueError) with the message, line and column.
A common pattern merges loaded settings over defaults: {**DEFAULTS, **loaded}.
Syntax
- dump/load for files.
- dumps/loads for strings.
- indent for readability.
Code examples
Saving and loading
True python
Python to JSON and back
{"ok": true, "missing": null, "pair": [1, 2]}
{'ok': True, 'n': 1.5}More examples
A settings store with defaults
{'theme': 'light', 'font_size': 14}
{'theme': 'dark', 'font_size': 14, 'greeting': 'नमस्ते'}
corrupt settings: Expecting property name enclosed in double quotes
{'theme': 'light', 'font_size': 14}Step-by-step explanation
- A missing file simply means 'use the defaults'.
- Saved values override defaults when merged, and new keys are kept.
- ensure_ascii=False stores the Hindi greeting as readable text; a corrupt file is reported and the defaults are used.
Expected output
Running “A settings store with defaults” prints exactly:
Practical applications
- Application settings and saved state.
- Data exchanged with web APIs.
Best practices
- Use indent for files people may read.
- Handle FileNotFoundError and JSONDecodeError.
- Convert dates and sets explicitly.
Common mistakes
Saving unsupported types
Avoid
Prefer
Sets aren't JSON-serialisable; convert them to lists.
Confusing dump and dumps
Avoid
Prefer
dump writes to a file and returns None; dumps returns a string.
Important notes
- json.dumps(obj, default=str) converts unknown types with str() as a quick fallback.
Key takeaways
- json.dump/load for files, dumps/loads for strings.
- dict↔object, list↔array, None↔null.
- Invalid JSON raises JSONDecodeError.
Try it yourself
- 1Save a list of contacts (name, phone, tags) to JSON and load it back.
- 2Write a high-score file that keeps the top five scores between runs.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?