Sub topic 1
Opening Files Safely and Working with JSON
Prerequisites
Assume you know basic Python syntax, dictionaries, lists, strings, functions, exceptions, and the with statement for opening files.
Opening Files Safely
Python opens files in text mode by default when you use open(). Specify the encoding instead of relying on the operating system’s default. UTF-8 is a common choice because it supports many languages.
Use newline="" for CSV files. The csv module then controls line endings correctly on different platforms. JSON files do not need this argument.
from pathlib import Path
path = Path("config.json")
with path.open("w", encoding="utf-8") as file:
file.write('{"city": "Zürich"}')
with path.open(encoding="utf-8") as file:
text = file.read()
print(text)What JSON Is and How It Maps to Python Types
JSON, or JavaScript Object Notation, is a text format for structured data. JSON objects use quoted keys and map to Python dictionaries. JSON arrays map to lists.
| JSON value | Python value |
|---|---|
| object | `dict` |
| array | `list` |
| string | `str` |
| number | `int` or `float` |
| `true`, `false`, `null` | `True`, `False`, `None` |
JSON does not support Python-specific values such as tuples, sets, or datetime objects directly.
flowchart TD
A[JSON text] --> B[json.loads]
B --> C[Python objects]
C --> D[json.dumps]
D --> AReading and Writing JSON
The json module provides two pairs of functions:
loadsanddumpswork with strings.loadanddumpwork with open file objects.
import json
text = '{"name": "Ada", "active": true, "scores": [10, 12]}'
data = json.loads(text)
print(data["name"], data["active"])
with open("user.json", "w", encoding="utf-8") as file:
json.dump(data, file)json.loads() raises json.JSONDecodeError when the text is malformed, such as when an object has a trailing comma.
Formatting JSON Output
Use indent to make output easier to read. Use sort_keys=True for stable ordering, which helps with reviews and tests. Set ensure_ascii=False to preserve readable non-ASCII characters.
print(json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False))These options affect formatting, not the underlying data.
Exercise
Which function should you use to convert a JSON string into a Python dictionary?
Show answer
Use json.loads(). Use json.load() when reading JSON from an open file.