# 值错误：检测到循环引用

- **ID:** `python/flask-jsonify-circular-reference`
- **领域:** python
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

使用Flask的jsonify序列化具有循环引用的Python对象（如自引用ORM模型或图结构）时，jsonify没有处理循环的解析器，导致抛出循环引用错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (90% 成功率)
   ```
   Use a custom JSON encoder that tracks visited objects, or convert to a serializable dict by breaking cycles first. Example: `def serialize(obj, seen=None): if id(obj) in seen: return None; seen.add(id(obj)); return {k: serialize(v, seen) for k, v in obj.__dict__.items()}`
   ```
2. **** (85% 成功率)
   ```
   Use a library like `flask-marshmallow` or `marshmallow` with `fields.Nested` and `exclude` to avoid cycles.
   ```

## 无效尝试

- **** — json.dumps with default=str only converts non-serializable objects to strings, but circular references cause infinite recursion before reaching that fallback. (95% 失败率)
- **** — Using Flask's app.json_encoder with a custom encoder does not automatically handle circular references; it still recurses infinitely unless explicitly checked. (90% 失败率)
