容易json转换格式

This commit is contained in:
zk
2026-04-23 18:23:44 +08:00
parent 8fbb1f6fca
commit 9ee66ffa6a
+21 -4
View File
@@ -1,15 +1,32 @@
"""AI 输出 JSON 解析工具 """AI 输出 JSON 解析工具
将 LLM 返回的可能带 markdown 代码块包裹的文本解析为 Python 对象。 将 LLM 返回的可能带 markdown 代码块、思考标签等包裹的文本解析为 Python 对象。
""" """
import re import re
from json_repair import repair_json from json_repair import repair_json
# 匹配 <think>任意内容</think>,用于剥离 DeepSeek R1 等推理模型的思考过程
# re.DOTALL 让 . 匹配换行,re.IGNORECASE 忽略大小写
# .*? 非贪婪匹配,避免跨多个 think 标签
_THINK_RE = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)
# 匹配 ```json ... ``` 代码块,提取中间的 JSON 内容
# (?:json\w*)? — 可选的语言标记,兼容 json / JSON / jsonc 等,也兼容无标记的裸 ```
# \s*\n? — 跳过语言标记后的空白和换行
# (.*?) — 非贪婪捕获代码块内容(第1组)
# \n?\s*``` — 匹配结尾的 ```
_CODE_BLOCK_RE = re.compile(r"```(?:json\w*)?\s*\n?(.*?)\n?\s*```", re.DOTALL | re.IGNORECASE)
def parse_llm_json(text: str): def parse_llm_json(text: str):
"""解析 AI 输出的 JSON,自动去除 markdown 代码块包裹,容错处理""" """解析 AI 输出的 JSON,自动去除思考标签、markdown 代码块,容错处理"""
cleaned = re.sub(r"^```(?:json)?\s*\n?", "", text.strip()) # 1. 去掉 <think>...</think> 思考内容
cleaned = re.sub(r"\n?```\s*$", "", cleaned) cleaned = _THINK_RE.sub("", text).strip()
# 2. 如果有 ```json ... ``` 代码块,只取代码块里的内容
match = _CODE_BLOCK_RE.search(cleaned)
if match:
cleaned = match.group(1).strip()
# 3. repair_json 容错解析:修复不规范的 JSON(多余逗号、缺引号等)
return repair_json(cleaned, return_objects=True) return repair_json(cleaned, return_objects=True)