liveBook · Manning

Serialization

As explained in Python How-To

Serialization is the process of converting native program objects or values into a JSON representation.

Serialization converts native Python objects or values into JSON data for an outgoing communication route. The json module provides dumps for producing a JSON string and dump for writing JSON directly to a file. section 9.3.4 section 9.3.5

For built-in data, json.dumps performs predictable conversions:

  • Python strings become JSON strings with double quotes; False becomes false; None becomes null. section 9.3.4
  • Dictionary keys become JSON strings, so the Python key 1 becomes the JSON key "1". section 9.3.4
  • Tuples are JSON-serializable and become JSON arrays after serialization. section 9.3.6
  • Custom class instances are not JSON-serializable by default because the encoder cannot know which attributes or metadata to include. section 9.3.4

Serializing a custom object

A fallback encoder can convert a Task instance through its __dict__ representation: dumped_task = json.dumps(tasks[0], default=lambda x: x.__dict__) print(dumped_task) # {"title": "Laundry", "desc": "Wash clothes", "urgency": 3} The default argument supplies instructions for objects the encoder cannot handle. Choose the representation deliberately, because it determines which object data crosses the system boundary. section 9.3.4

Readable output can use indent=2, while sort_keys=True produces stable alphabetical key ordering. JSON serialization and deserialization form opposite directions: Python data becomes JSON, and JSON becomes native Python data. section 9.3.4 section 9.6

How Python How-To covers it

How deep it goes
Explains built-in conversions, encoder failures, fallback handling, formatting, and file methods, but defers broader custom encoding alternatives.
Examples
Uses built-in lists, Task objects, formatted dictionaries, sorted user information, and a named-tuple User object.
What it assumes
Assumes familiarity with Python objects and classes while teaching JSON conversion from native data through concrete examples.
What you can do after
Apply serialization with Python's json module and provide fallback encoding instructions for custom class instances.
How it connects
Connects JSON serialization with JSON deserialization, custom classes, named tuples, and data exchange between systems.

Also explained in

Compare how 24 books explain serialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.