這個簡單的軟件包可用於修復無效的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