json-fix
raw JSON → 1.0.2 verified Mon Apr 27 auth: no python
A library that allows custom JSON serialization for any class by adding a __json__ method, seamlessly patching the built-in json module. Current version 1.0.2, updated periodically.
pip install json-fix Common errors
error TypeError: Object of type MyClass is not JSON serializable ↓
cause The import 'import json_fix' is missing or the class does not have a __json__ method.
fix
Add 'import json_fix' at the top of your script and define a __json__ method on your class that returns a serializable object.
error json_fix not found ↓
cause The package is not installed.
fix
Run 'pip install json-fix' to install the package.
Warnings
breaking json_fix patches the built-in json module globally. If other code relies on the original behavior (e.g., raising TypeError on non-serializable objects), it may break. ↓
fix Ensure no other code depends on json raising TypeError for custom objects without __json__.
gotcha The __json__ method must return a JSON-serializable object (dict, list, string, etc.), not a raw JSON string. Returning a string will double-encode it. ↓
fix Return a native Python object (e.g., dict) from __json__; do not call json.dumps inside it.
gotcha json_fix only works with the built-in json module. It does not affect third-party serializers like orjson, rapidjson, or ujson. ↓
fix Use built-in json module for serialization when using json_fix.
Imports
- json_fix wrong
from json_fix import ...correctimport json_fix
Quickstart
import json
import json_fix
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __json__(self):
return {"name": self.name, "age": self.age}
person = Person("Alice", 30)
print(json.dumps(person)) # {"name": "Alice", "age": 30}