python中实现json-repair快速修复损坏的JSON文件
作者:风华浪浪
一、背景
- 本人场景:大模型提示词要求返回json格式类型,但是却```json开头,以```结尾, 或者少引号等各种情况
- 修复 JSON 中的语法错误
缺少引号、错误放置的逗号、未转义的字符以及不完整的键值对。
缺少引号、格式不正确的值(true、false、null)以及修复损坏的键值结构。 - 修复格式错误的 JSON 数组和对象
通过添加必要的元素(例如,逗号、括号)或默认值(null、“”)导致数组/对象不完整或损坏。
该库可以处理包含额外非 JSON 字符(如注释或位置不正确的字符)的 JSON,并在保持有效结构的同时清理它们。 - 自动完成缺失的 JSON 值
自动使用合理的默认值(如空字符串或 null)完成 JSON 字段中缺失的值,确保有效性。
二、安装与参数
此库来完全替换json.loads()等
pip install json-repair
json_repair -h
usage: json_repair [-h] [-i] [-o TARGET] [--ensure_ascii] [--indent INDENT] [filename]
Repair and parse JSON files.
positional arguments:
filename The JSON file to repair (if omitted, reads from stdin)
options:
-h, --help show this help message and exit
-i, --inline Replace the file inline instead of returning the output to stdout
-o TARGET, --output TARGET
If specified, the output will be written to TARGET filename instead of stdout
--ensure_ascii Pass ensure_ascii=True to json.dumps()
--indent INDENT Number of spaces for indentation (Default 2)
三、使用示例
少引号
from json_repair import repair_json, loads
json_string = repair_json("{'test_chinese_ascii':'统一码, }", ensure_ascii=False)
print(json_string)
{"test_chinese_ascii": "统一码"}
json_data = loads(json_string)
print(type(json_data), json_data)
<class 'dict'> {'test_chinese_ascii': '统一码'}
有时大模型提示词说返回jison格式类型,但是却```json开头,以```结尾, 或者少引号等各种情况
json_string = "```json{'username': 'zhangsan', 'age': 13, 'phone': 13312345678, 'description': 'hello world'}```"
repair_data = repair_json(json_string)
print(repair_data)
{"username": "zhangsan", "age": 13, "phone": 13312345678, "description": "hello world"}
json_data = loads(json_string)
print(type(json_data), json_data)
<class 'dict'> {'username': 'zhangsan', 'age': 13, 'phone': 13312345678, 'description': 'hello world'}
处理报错 json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
序列化报错
import json
json_string = "{'start_row': 0, 'end_row': 0, 'env': 0, 'now': 0}"
json_data = json.loads(json_string)
print(json_data)
序列化正确
json_string = "{'start_row': 0, 'end_row': 0, 'env': 0, 'now': 0}"
json_data = loads(json_string)
print(type(json_data), json_data)
四、注意
避免这种反模式
这是很浪费的,因为json_repair它已经为您验证了 JSON 是否有效,
如果您仍然想这样做,那么请skip_json_loads=True按照下面部分所述添加到调用中
obj = {}
try:
obj = json.loads(string)
except json.JSONDecodeError as e:
obj = json_repair.loads(string)
...
使用中文字符需要添加ensure_ascii=False
repair_json("{'test_chinese_ascii':'统一码'}")
{"test_chinese_ascii": "\u7edf\u4e00\u7801"}
repair_json("{'test_chinese_ascii':'统一码'}", ensure_ascii=False)
{"test_chinese_ascii": "统一码"}
性能注意事项
如果你发现这个库因为正在使用而太慢,json.loads()你可以通过传递skip_json_loads=True给来跳过它repair_json
from json_repair import repair_json good_json_string = repair_json(bad_json_string, skip_json_loads=True)
我选择不使用任何快速 json 库以避免任何外部依赖,以便任何人都可以使用它,无论他们的堆栈如何。
设置return_objects=True总是会更快,因为解析器已经返回一个对象,并且它没有将该对象序列化为 JSONskip_json_loads只有当你 100% 确定该字符串不是有效的 JSON 时才会更快
如果您在转义时遇到问题,请将字符串作为**原始字**符串传递,例如:r"string with escaping\""
到此这篇关于python中实现json-repair快速修复损坏的JSON文件的文章就介绍到这了,更多相关python json-repair修复损坏JSON文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
