解决gpt返回json Python没法解析的情况

import re
import json
def replace_newlines(match):
    # 在匹配的字符串中替换 \n 和 \r
    return match.group(0).replace('\n', '\\n').replace('\r', '\\r')

def clean_json_str(json_str: str) -> str:
    """
    生成的json格式可能不标准,先进行替换处理
    :param json_str:
    :return:
    """
    json_str = json_str.replace("None","null")

    # 去除代码块符号```
    #json字符串中None换成null
    json_str = json_str.replace("None","null")

    match = re.search(r'```json(.*?)```', json_str, re.DOTALL)
    if match:
        json_str = match.group(1)
    match = re.search(r'```(.*?)```', json_str, re.DOTALL)
    if match:
        json_str = match.group(1)
    # 在匹配的字符串中替换 \n 和 \r
    json_str = re.sub( r'("(?:\\.|[^"\\])*")', replace_newlines, json_str)
    # 移除键值对后面多余的逗号
    json_str = re.sub(r',\s*}', '}', json_str)
    json_str = re.sub(r',\s*]', ']', json_str)
    # 修复缺少的逗号
    json_str = re.sub(r'\"\s+\"', '\",\"', json_str)
    # True、False替换
    json_str = json_str.replace("True","true")
    json_str = json_str.replace("False","false")
    return json_str

def clean_and_load_json(json_str) -> dict:
    """
    不标准json字符串修正后返回dict对象
    :param json_str:
    :return: dict对象,解析失败返回{}
    """
    try:
        json_str = clean_json_str(json_str)
        return json.loads(json_str)
    except Exception as e:
        print(e)

posted @ 2024-01-31 09:35  小小咸鱼YwY  阅读(142)  评论(0编辑  收藏  举报