JSON Serialization & Parsing (dumps, loads)
Bridge Python data structures and JSON strings: serializing dicts and lists with json.dumps(), parsing JSON with json.loads(), mapping Python types (None, True, tuples), and solving serialization errors with custom encoders.
The json Module: Strings vs Streams
JSON (JavaScript Object Notation) is the universal format for web APIs, configuration files, and cross-language data exchange. Python's standard library json module provides four primary functions differentiated by an 's' suffix.
Functions ending in 's' operate on strings: json.dumps(obj) serializes a Python object into a JSON string in memory, and json.loads(str) deserializes a JSON string back into native Python types.
Functions without 's' operate directly on file streams: json.dump(obj, file_obj) writes JSON directly into an open file, and json.load(file_obj) reads and parses JSON from an open file stream.
Python vs JSON Type Mappings
JSON syntax and Python syntax are similar but not identical. The json module performs automatic two-way translation between them.
Python dictionaries map to JSON objects {}; Python lists and tuples map to JSON arrays [].
Crucially, boolean literals map between capital and lowercase: Python True becomes JSON true, and False becomes false. Python's None singleton translates to JSON's null. Strings always serialize to double quotes " in valid JSON, even if defined using single quotes ' in Python.
Handling Dates, Sets, and Custom Encoders
The standard JSON specification only supports objects, arrays, strings, numbers, booleans, and null. Python structures like set, datetime.date, Decimal, and custom class instances cannot be serialized out-of-the-box.
When encountering an unsupported type, json.dumps() raises TypeError: Object of type X is not JSON serializable.
To resolve this, supply a custom conversion function to the default parameter of json.dumps(), e.g. default=str or default=lambda o: list(o) if isinstance(o, set) else o.__dict__.
The JSON Translation Conveyor
Transform Python dictionaries into compliant JSON strings and vice-versa. Test what happens when serializing unsupported types like sets or datetimes, and see how the default parameter resolves serialization errors.
". Single quotes ' are illegal in JSON and will raise a json.decoder.JSONDecodeError.Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- dumps/loads operate on memory strings; dump/load operate directly on file streams.
- Python None maps to JSON null; True/False map to lowercase true/false.
- JSON strictly requires double quotes (") for strings and keys; single quotes trigger JSONDecodeError.
- Tuples serialize into JSON arrays, and deserialize back into Python lists.
- Pass a custom callable to default in json.dumps() to serialize sets, dates, and custom objects.
Done with this concept?
Mark it complete to track your progress. No login needed.