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)
解決gpt返回json Python沒法解析的情況
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.