| domain | contrib |
|---|---|
| title | JSON 解析失败Handling — 截断 / 格式Error |
| verification | metadata-normalized |
| created | 2026-07-06 |
| source | unknown |
---{"title": "JSON 解析失败Handling — 截断 / 格式Error", "domain": "devops", "tags": ["json", "parse", "truncated", "llm", "output"]}---
从 LLM 输出或 API 返回中解析 JSON 时报 json.decoder.JSONDecodeError。常见于模型输出被截断、前后有多余字符。
- 模型输出在 JSON 完成前被截断(token 限制)
- 模型在 JSON 前后加了 markdown 代码块标记
json ... - JSON 内容含未转义的特殊字符
- Follow the solution steps in order
- Run any relevant commands or tests to confirm the fix
- Verify the symptom no longer occurs
- Check related logs or outputs for expected behavior
import json
import re
def safe_json_parse(text: str) -> dict | None:
"""尝试多种策略解析 JSON"""
# 策略 1:直接解析
try:
return json.loads(text)
except json.JSONDecodeError:
pass
# 策略 2:提取代码块中的 JSON
m = re.search(r'```(?:json)?\s*\n?(.*?)\n?```', text, re.DOTALL)
if m:
try:
return json.loads(m.group(1))
except json.JSONDecodeError:
pass
# 策略 3:提取第一个 { } 间的完整内容
m = re.search(r'(\{.*\})', text, re.DOTALL)
if m:
try:
return json.loads(m.group(1))
except json.JSONDecodeError:
pass
# 策略 4:使用 strict=False(允许控制字符)
try:
return json.loads(text, strict=False)
except json.JSONDecodeError:
pass
return None
# JSON 解析失败Handling — 截断 / 格式Error
result = safe_json_parse(model_output)
if result is None:
print("JSON 解析失败,尝试重新生成")