python中實(shí)現(xiàn)json-repair快速修復(fù)損壞的JSON文件
一、背景
- 本人場(chǎng)景:大模型提示詞要求返回json格式類(lèi)型,但是卻```json開(kāi)頭,以```結(jié)尾, 或者少引號(hào)等各種情況
- 修復(fù) JSON 中的語(yǔ)法錯(cuò)誤
缺少引號(hào)、錯(cuò)誤放置的逗號(hào)、未轉(zhuǎn)義的字符以及不完整的鍵值對(duì)。
缺少引號(hào)、格式不正確的值(true、false、null)以及修復(fù)損壞的鍵值結(jié)構(gòu)。 - 修復(fù)格式錯(cuò)誤的 JSON 數(shù)組和對(duì)象
通過(guò)添加必要的元素(例如,逗號(hào)、括號(hào))或默認(rèn)值(null、“”)導(dǎo)致數(shù)組/對(duì)象不完整或損壞。
該庫(kù)可以處理包含額外非 JSON 字符(如注釋或位置不正確的字符)的 JSON,并在保持有效結(jié)構(gòu)的同時(shí)清理它們。 - 自動(dòng)完成缺失的 JSON 值
自動(dòng)使用合理的默認(rèn)值(如空字符串或 null)完成 JSON 字段中缺失的值,確保有效性。
二、安裝與參數(shù)
此庫(kù)來(lái)完全替換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)
三、使用示例
少引號(hào)
from json_repair import repair_json, loads
json_string = repair_json("{'test_chinese_ascii':'統(tǒng)一碼, }", ensure_ascii=False)
print(json_string)
{"test_chinese_ascii": "統(tǒng)一碼"}
json_data = loads(json_string)
print(type(json_data), json_data)
<class 'dict'> {'test_chinese_ascii': '統(tǒng)一碼'}
有時(shí)大模型提示詞說(shuō)返回jison格式類(lèi)型,但是卻```json開(kāi)頭,以```結(jié)尾, 或者少引號(hào)等各種情況
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'}
處理報(bào)錯(cuò) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
序列化報(bào)錯(cuò)
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)
四、注意
避免這種反模式
這是很浪費(fèi)的,因?yàn)閖son_repair它已經(jīng)為您驗(yàn)證了 JSON 是否有效,
如果您仍然想這樣做,那么請(qǐng)skip_json_loads=True按照下面部分所述添加到調(diào)用中
obj = {}
try:
obj = json.loads(string)
except json.JSONDecodeError as e:
obj = json_repair.loads(string)
...
使用中文字符需要添加ensure_ascii=False
repair_json("{'test_chinese_ascii':'統(tǒng)一碼'}")
{"test_chinese_ascii": "\u7edf\u4e00\u7801"}
repair_json("{'test_chinese_ascii':'統(tǒng)一碼'}", ensure_ascii=False)
{"test_chinese_ascii": "統(tǒng)一碼"}
性能注意事項(xiàng)
如果你發(fā)現(xiàn)這個(gè)庫(kù)因?yàn)檎谑褂枚?code>json.loads()你可以通過(guò)傳遞skip_json_loads=True給來(lái)跳過(guò)它repair_json
from json_repair import repair_json good_json_string = repair_json(bad_json_string, skip_json_loads=True)
我選擇不使用任何快速 json 庫(kù)以避免任何外部依賴,以便任何人都可以使用它,無(wú)論他們的堆棧如何。
設(shè)置return_objects=True總是會(huì)更快,因?yàn)榻馕銎饕呀?jīng)返回一個(gè)對(duì)象,并且它沒(méi)有將該對(duì)象序列化為 JSONskip_json_loads只有當(dāng)你 100% 確定該字符串不是有效的 JSON 時(shí)才會(huì)更快
如果您在轉(zhuǎn)義時(shí)遇到問(wèn)題,請(qǐng)將字符串作為**原始字**符串傳遞,例如:r"string with escaping\""
到此這篇關(guān)于python中實(shí)現(xiàn)json-repair快速修復(fù)損壞的JSON文件的文章就介紹到這了,更多相關(guān)python json-repair修復(fù)損壞JSON文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python打包代碼成exe可執(zhí)行文件的方法總結(jié)
將Python代碼打包成可執(zhí)行文件(.exe)是一種非常有效的解決方案,能夠使用戶無(wú)需安裝Python環(huán)境即可直接運(yùn)行程序,本文整理了一些常見(jiàn)的方法,希望對(duì)大家有所幫助2024-10-10
基于深度學(xué)習(xí)和OpenCV實(shí)現(xiàn)目標(biāo)檢測(cè)
這篇文章主要介紹了通過(guò)使用OpenCV進(jìn)行基于深度學(xué)習(xí)的對(duì)象檢測(cè)以及使用OpenCV檢測(cè)視頻,文中的示例代碼講解詳細(xì),需要的可以參考一下2021-12-12
Python實(shí)現(xiàn)完整的事務(wù)操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)完整的事務(wù)操作,結(jié)合實(shí)例形式分析了Python操作mysql數(shù)據(jù)庫(kù)相關(guān)事務(wù)操作的具體流程與實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-06-06
Pandas時(shí)間數(shù)據(jù)處理詳細(xì)教程
日常工作中日期格式有多種表達(dá)形式,比如年份開(kāi)頭或是月份開(kāi)頭2022/6/4、6/4/2022等,通過(guò)pandas的日期數(shù)據(jù)處理,這篇文章主要給大家介紹了關(guān)于Pandas時(shí)間數(shù)據(jù)處理的相關(guān)資料,需要的朋友可以參考下2023-01-01
python 存儲(chǔ)json數(shù)據(jù)的操作
這篇文章主要介紹了python 存儲(chǔ)json數(shù)據(jù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-05-05
關(guān)于Python?Selenium自動(dòng)化導(dǎo)出新版WOS(web?of?science)檢索結(jié)果的問(wèn)題
這篇文章主要介紹了Python?Selenium自動(dòng)化導(dǎo)出新版WOS(web?of?science)檢索結(jié)果,本代碼屬于半自動(dòng)化導(dǎo)出,考慮到開(kāi)發(fā)效率等因素,有兩處在首次導(dǎo)出時(shí)需要手動(dòng)操作,具體實(shí)現(xiàn)過(guò)程跟隨小編一起看看吧2022-01-01

