Learning navigation

Code with Animation

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.

Python7 min readConcept 20 of 24

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.

Select JSON Translation Protocol:
# 1. Standard json module:
import json
# 2. Python dictionary:
data = {"user": "Alice", "admin": True, "bio": None}
# 3. Serialize to JSON:
json_str = json.dumps(data)
# {"user": "Alice", "admin": true, "bio": null}
PYTHON ⇄ JSON TYPE TRANSLATION CONVEYORINPUT: PYTHON DICTPython Syntax:True, None, dict()Native in-memory typesdumps()OUTPUT: JSON STRINGJSON Format:true, null, "{}"Double-quoted stringNone ➔ nullTrue ➔ trueFalse ➔ falsetuple ➔ arraySERIALIZATION: In-memory Python dictionary to compliant JSON string✓ Automatically converts None to null, and booleans to lowercase
★ Python Rule: JSON strictly mandates double quotes ". 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.

  1. 1What does `json.loads('{"active": true, "user": null}')` return in Python?
  2. 2What is the difference between `json.dumps()` and `json.dump()`?
  3. 3Why does `json.dumps({'ids': {1, 2, 3}})` raise a `TypeError`?

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.