python
type_error
ai_generated
true
TypeError: User 类型的对象无法进行 JSON 序列化
TypeError: Object of type User is not JSON serializable
ID: python/sqlalchemy-json-serialization-error
80%修复率
87%置信度
0证据数
2024-03-25首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.4.x | active | — | — | — |
| 2.0.x | active | — | — | — |
根因分析
尝试直接用 json.dumps() 序列化 SQLAlchemy 模型实例,而没有自定义编码器。
English
Trying to serialize SQLAlchemy model instances directly with json.dumps() without a custom encoder.
解决方案
-
90% 成功率
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% 成功率
Convert to dict first: user_dict = {c.name: getattr(user, c.name) for c in user.__table__.columns}
无效尝试
常见但无效的做法:
-
80% 失败
Returns the object's string representation, not the data.
-
70% 失败
Converts all non-serializable objects to strings, losing structure.