|
@@ -13,6 +13,9 @@ def parse_general_json(response_text, key=None):
|
|
|
:param key: 若指定,则从解析结果中提取该键对应的值,默认为 None
|
|
|
:return: 解析结果,如果指定了 key 则返回对应的值,解析失败返回 None
|
|
|
"""
|
|
|
+
|
|
|
+ # 处理字符串未闭合的情况,尝试修正
|
|
|
+ response_text = fix_unclosed_string(response_text)
|
|
|
try:
|
|
|
# 优先尝试使用 orjson.loads 解析标准 JSON 格式
|
|
|
data = orjson.loads(response_text.strip())
|
|
@@ -32,6 +35,30 @@ def parse_general_json(response_text, key=None):
|
|
|
return None
|
|
|
return data
|
|
|
|
|
|
+def fix_unclosed_string(text):
|
|
|
+ """
|
|
|
+ 尝试修复未闭合的字符串
|
|
|
+ :param text: 输入的文本
|
|
|
+ :return: 修复后的文本
|
|
|
+ """
|
|
|
+ try:
|
|
|
+ # 查找未闭合的字符串
|
|
|
+ open_quotes = []
|
|
|
+ for _, char in enumerate(text):
|
|
|
+ if char in ['"', "'"]:
|
|
|
+ if open_quotes and open_quotes[-1] == char:
|
|
|
+ open_quotes.pop()
|
|
|
+ else:
|
|
|
+ open_quotes.append(char)
|
|
|
+
|
|
|
+ if open_quotes:
|
|
|
+ # 如果存在未闭合的字符串,尝试在末尾添加闭合引号
|
|
|
+ closing_quote = open_quotes[-1]
|
|
|
+ text = text.rstrip() + closing_quote
|
|
|
+
|
|
|
+ return text
|
|
|
+ except:
|
|
|
+ return text
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
# 测试正常解析情况 - 标准 JSON(双引号)
|