梦应逍遥 发表于 2025-6-7 03:28:32

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]

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总是会更快,因为分析器已经返回一个对象,而且它没有将该对象序列化为 JSON
skip_json_loads只有当你 100% 确定该字符串不是有效的 JSON 时才会更快
如果您在转义时碰到问题,请将字符串作为**原始字**符勾通报,比方:r"string with escaping\""
页: [1]
查看完整版本: python 之 json-repair 一个牛掰修复无效的 json的库