python type_error ai_generated true

TypeError: User 类型的对象无法进行 JSON 序列化

TypeError: Object of type User is not JSON serializable

ID: python/sqlalchemy-json-serialization-error

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 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)
  2. 85% 成功率
    Convert to dict first: user_dict = {c.name: getattr(user, c.name) for c in user.__table__.columns}

无效尝试

常见但无效的做法:

  1. 80% 失败

    Returns the object's string representation, not the data.

  2. 70% 失败

    Converts all non-serializable objects to strings, losing structure.