简介
大模型生成的 JSON 数据往往存在格式瑕疵,比如缺少引号、逗号位置错误或键值对不完整。json-repair 库能自动识别并修复这些语法错误,确保数据可被标准解析器处理。
安装
pip install json-repair
核心用法
基础修复
最直接的用法是将损坏的字符串修复为合法的 JSON 字符串:
from json_repair import repair_json
bad_json_string = "{'name': 'Alice', 'age': 20}"
good_json_string = repair_json(bad_json_string)
# 输出:{"name": "Alice", "age": 20}
替代 json.loads
你可以直接用 repair_json.loads() 替代标准库的 json.loads(),它会在内部尝试修复后再解析:
import json_repair
decoded_object = json_repair.loads(json_string)
如果希望直接获取 Python 对象而非 JSON 字符串,可以设置 return_objects=True:
decoded_object = json_repair.repair_json(json_string, return_objects=True)
常见场景示例
1. 单引号问题 LLM 有时会生成 Python 字典风格的字符串(单引号),标准 JSON 解析器无法处理。
broken_json = "{'name': 'Alice', 'age': 20}"
result = repair_json(broken_json)
print(result) # {"name": "Alice", "age": 20}
2. 多余逗号与注释 JSON 不支持尾随逗号或注释,但修复库能智能清理。
broken_json = '[1, 2, 3, ]'
result = repair_json(broken_json)
commented_json = '{ // 这是一条注释 "id": 123 }'
result = repair_json(commented_json)
3. LLM 非结构化输出 当模型在 JSON 前后夹杂自然语言时,该库也能提取有效部分。
bad_json_string = '你好,这是我按照 json 格式返回的数据:{"name": "John", "age": 30}'
good_json_string = repair_json(bad_json_string)
data = json.loads(good_json_string)
print(data)
性能优化
默认情况下,库会先调用 json.loads() 验证输入。如果你确定输入无效且需要修复,可以通过 跳过验证步骤以提升速度:

