使用json_repair修复大模型的json输出错误
json_repair
有些 LLM 在返回格式正确的 JSON 数据时会有些问题,有时会漏掉括号,有时会在数据中添加一些单词。不至于这种错误每次都要丢弃,再次生成太浪费时间了,因此能修复错误时还是要尽量修复。这就是 json_repair
的主要目的:修复 LLM 在生成 json 数据时的错误。
- 修复 JSON 中的语法错误
- 缺少引号、逗号位置错误、未转义的字符以及不完整的键值对。
- 缺少引号、格式不正确的值(true、false、null)以及修复损坏的键值结构。
- 修复格式错误的 JSON 数组和对象
- 通过添加必要的元素(例如逗号、括号)或默认值(null、“”)来修复不完整或损坏的数组/对象。
- 该库可以处理包含额外非 JSON 字符(例如注释或位置不正确的字符)的 JSON,并在保持有效结构的同时进行清理。
- JSON 缺失值自动补全
- 使用合理的默认值(例如空字符串或 null)自动补全 JSON 字段中的缺失值,确保有效性。
安装
!pip install json-repair
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/, https://mirrors.aliyun.com/pypi/simple/, https://pypi.mirrors.ustc.edu.cn/simple/
Requirement already satisfied: json-repair in /home/guest/anaconda3/envs/xprepo/lib/python3.11/site-packages (0.41.1)
使用
以常见的字段内部的多余""为例
import json
import json_repair
from json_repair import repair_jsonbad_json_string = """```json
{"title": "Daily Thoughts","mood": ""relaxed"","content": "Today I felt really "productive" and relaxed."
}
“”"
a_str = bad_json_string
try:
obj = json.loads(a_str)
except json.JSONDecodeError as e:
print(“Attempting to fix the JSON string…”)
# solution 1. fix the json string
a_str = repair_json(a_str)
obj = json.loads(a_str)
# solution 1. fix the json string and load as json
# obj = json_repair.loads(a_str)
finally:
print(json.dumps(obj, indent=2))
Attempting to fix the JSON string...{"title": "Daily Thoughts","mood": "relaxed","content": "Today I felt really \"productive\" and relaxed."}