这个简单的软件包可用于修复无效的JSON字符串。要了解此软件包工作的所有情况,请查看单元测试。
如果您觉得这个图书馆有用,可以在这里向我的每月啤酒预算捐款来帮助我:https://github.com/sponsors/mangiucugna
如果您不确定此库是否会解决您的特定问题,或者只是希望在线验证JSON,则可以访问github页面上的演示网站:https://mangiucugna.github.io/json_repair/
或听到Google Notebooklm生成的音频介绍的音频介绍
在返回形成良好的JSON数据时,有些LLM有点不合时宜,有时它们会跳过括号,有时他们在其中添加了一些单词,因为这是LLM的作用。幸运的是,LLMS犯的错误足够简单,无法修复而不会破坏内容。
我搜索了一个轻巧的Python软件包,该软件包能够可靠地解决此问题,但找不到任何问题。
所以我写了一个
作为我工作的一部分,我们使用OpenAI API,我们注意到即使结构化输出有时,结果也不是完全有效的JSON。因此,我们仍然使用此库来涵盖这些异常值。
使用PIP安装库
pip install json-repair
那么您可以在代码中使用它
from json_repair import repair_json
good_json_string = repair_json(bad_json_string)
# If the string was super broken this will return an empty string
您可以使用此库完全替换json.loads()
:
import json_repair
decoded_object = json_repair.loads(json_string)
或只是
import json_repair
decoded_object = json_repair.repair_json(json_string, return_objects=True)
该库的一些用户采用以下模式:
obj = {}
try:
obj = json.loads(string)
except json.JSONDecodeError as e:
obj = json_repair.loads(string)
...
这是浪费的,因为json_repair
如果JSON有效,则将为您验证,如果您仍然要这样做,请添加skip_json_loads=True
将其添加到呼叫中,如下所述。
JSON维修还提供了json.load()
的置换替换:
import json_repair
try:
file_descriptor = open(fname, 'rb')
except OSError:
...
with file_descriptor:
decoded_object = json_repair.load(file_descriptor)
以及另一种从文件中读取的方法:
import json_repair
try:
decoded_object = json_repair.from_file(json_file)
except OSError:
...
except IOError:
...
请记住,图书馆不会捕获任何与IO相关的例外,这些例外将需要由您管理
当使用非拉丁蛋白字符(例如中文,日语或韩语)时,您需要通过ensure_ascii=False
将其传递给repair_json()
以保留输出中的非拉丁字符。
这是使用汉字的示例:
repair_json("{'test_chinese_ascii':'统一码'}")
会返回
{"test_chinese_ascii": "u7edfu4e00u7801"}
而是通过ensure_ascii=False
:
repair_json("{'test_chinese_ascii':'统一码'}", ensure_ascii=False)
会返回
{"test_chinese_ascii": "统一码"}
如果您发现此库太慢,因为使用json.loads()
可以通过传递skip_json_loads=True
to 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""
使用以下方式安装命令行的库
pipx 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
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)
请仅在主要版本上固定此库!
我们使用TDD且严格的语义版本控制,将进行频繁的更新,并且次要版本和补丁版本没有破坏变化。为了确保您仅在requirements.txt
中固定此库的主要版本,请指定包装名称,然后是主要版本和次要版本和补丁版本的通配符。例如:
json_repair==0.*
在此示例中,任何以0.
开头的版本。都可以接受,允许在次要版本和补丁版本上进行更新。
如果您在学术工作中使用此图书馆(我知道很多人),请在此处找到Bibtex:
@software{Baccianella_JSON_Repair_-_2024,
author = {Baccianella, Stefano},
month = aug,
title = {{JSON Repair - A python module to repair invalid JSON, commonly used to parse the output of LLMs}},
url = {https://github.com/mangiucugna/json_repair},
version = {0.28.3},
year = {2024}
}
感谢您援引我的工作,如果可以的话,请给我发送指向纸的链接!
该模块将按照BNF定义来解析JSON文件:
<json> ::= <primitive> | <container>
<primitive> ::= <number> | <string> | <boolean>
; Where:
; <number> is a valid real number expressed in one of a number of given formats
; <string> is a string of valid characters enclosed in quotes
; <boolean> is one of the literal strings 'true', 'false', or 'null' (unquoted)
<container> ::= <object> | <array>
<array> ::= '[' [ <json> *(', ' <json>) ] ']' ; A sequence of JSON values separated by commas
<object> ::= '{' [ <member> *(', ' <member>) ] '}' ; A sequence of 'members'
<member> ::= <string> ': ' <json> ; A pair consisting of a name, and a JSON value
如果出现问题(例如缺少括号或引号),它将使用一些简单的启发式方法来修复JSON字符串:
我确定会缺少某些角落的情况,如果您有示例,请打开问题,甚至更好地推动PR
只需创建一个带有requirements.txt
的虚拟环境。
确保在推动新提交后运行的github动作也不会失败。
您将需要所有者访问此存储库
pyproject.toml
并使用semver
符号适当更新版本编号python -m build