python
type_error
ai_generated
true
TypeError: Object of type User is not JSON serializable
ID: python/sqlalchemy-json-serialization-error
80%Fix Rate
87%Confidence
0Evidence
2024-03-25First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.4.x | active | — | — | — |
| 2.0.x | active | — | — | — |
Root Cause
Trying to serialize SQLAlchemy model instances directly with json.dumps() without a custom encoder.
generic中文
尝试直接用 json.dumps() 序列化 SQLAlchemy 模型实例,而没有自定义编码器。
Workarounds
-
90% success
Use a custom encoder: class UserEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, User): return {'id': obj.id, 'name': obj.name} return super().default(obj) -
85% success
Convert to dict first: user_dict = {c.name: getattr(user, c.name) for c in user.__table__.columns}
Dead Ends
Common approaches that don't work:
-
80% fail
Returns the object's string representation, not the data.
-
70% fail
Converts all non-serializable objects to strings, losing structure.