Serializing a Python Object to JSON
Author: Newtum
This guide demonstrates how to convert a custom Python object into a JSON string. The `json` module doesn't know how to encode custom objects by default, so we need to provide a way to do so.
The `TypeError` Problem
If you try to serialize a custom object directly with `json.dumps()`, you will get a `TypeError` because the JSON encoder only knows how to handle standard Python types.
Solution 1: Using a `default` function
You can pass a function to the `default` parameter of `json.dumps()`. This function will be called for objects that can't otherwise be serialized. It should return a serializable version of the object.
Solution 2: Subclassing `JSONEncoder`
For more complex or reusable serialization logic, you can subclass `json.JSONEncoder` and override its `default()` method.