python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python json-repair修复损坏JSON文件

python中实现json-repair快速修复损坏的JSON文件

作者:风华浪浪

本文主要介绍了python中实现json-repair快速修复损坏的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总是会更快,因为解析器已经返回一个对象,并且它没有将该对象序列化为 JSON
skip_json_loads只有当你 100% 确定该字符串不是有效的 JSON 时才会更快
如果您在转义时遇到问题,请将字符串作为**原始字**符串传递,例如:r"string with escaping\""

到此这篇关于python中实现json-repair快速修复损坏的JSON文件的文章就介绍到这了,更多相关python json-repair修复损坏JSON文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文