python代码修复字符串json数据格式问题,并将其按照字典形式读取

修复代码

python 复制代码
def aggressive_json_load(s):
    """
    终极修复:处理嵌套、残缺补齐、以及末尾多余的垃圾字符
    """
    if not isinstance(s, str): return None
    
    s = s.strip()
    if not (s.startswith('{') or s.startswith('[')): return None

    # 1. 尝试直接加载
    try:
        return json.loads(s)
    except json.JSONDecodeError:
        pass

    # 2. 括号平衡补齐逻辑
    def balance_json(text):
        stack = []
        for char in text:
            if char == '{': stack.append('}')
            elif char == '[': stack.append(']')
            elif char == '}':
                if stack and stack[-1] == '}': stack.pop()
            elif char == ']':
                if stack and stack[-1] == ']': stack.pop()
        return text + "".join(reversed(stack))

    # 3. 尝试修复多余的尾部字符(如案例中的 \n})
    # 逻辑:如果直接补齐不行,尝试截断到最后一个可能的闭合符再补齐
    trial_s = s
    while len(trial_s) > 0:
        fixed = balance_json(trial_s)
        try:
            return json.loads(fixed)
        except json.JSONDecodeError:
            # 删掉最后一个字符,继续尝试(处理尾部多余垃圾)
            trial_s = trial_s[:-1].rstrip()
            if not trial_s or trial_s[-1] not in ('"', '}', ']', 'e', 't', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
                # 优化性能:只有在可能结束的位置才尝试解析
                continue
                
    return None

def universal_cleaner(data):
    """
    递归扫描所有数据结构,自动解开所有嵌套 JSON 字符串
    """
    if isinstance(data, dict):
        return {k: universal_cleaner(v) for k, v in data.items()}
    elif isinstance(data, list):
        return [universal_cleaner(item) for item in data]
    elif isinstance(data, str):
        decoded = aggressive_json_load(data)
        if decoded is not None:
            # 递归处理"剥壳"后的内容
            return universal_cleaner(decoded)
        return data
    return data

测试

python 复制代码
raw_input = {
    "response": [
        # 情况 A: 带垃圾字符的字符串 JSON
        "{\"name\": \"cyclingSafety.checkHelmetSafety\", \"arguments\": {\"helmet_model\": \"SpeedSter Pro\"}}\n}", 
        # 情况 B: 正常的字典
        {
            "name": "cyclingSafety.checkHelmetSafety",
            "arguments": {"helmet_model": "MountainMaster X"}
        }
    ]
}

cleaned_data = universal_cleaner(raw_input)

# 打印验证结果
import pprint
pprint.pprint(cleaned_data)
相关推荐
卷心菜的学习路37 分钟前
基于多模态向量检索的数学相似题推荐系统:完整设计、算法与实验
java·python·算法·大模型·推荐算法·数学相似题
winfredzhang1 小时前
用 wxPython 打造「Claude Code 任务启动器」:一个把 AI CLI 变成一键工作流的桌面工具
python·wxpython·powershell·剪贴板·claudecodecli
Logintern091 小时前
DeepAgents 的子 Agent 如何实现上下文隔离
python
金銀銅鐵1 小时前
[Python] 借助 Turtle 来展示汉诺塔
python·数学
暴躁的小鸟1 小时前
附近口碑好的斜视配镜训练的眼视光中心
人工智能·python·深度学习
Data_Journal1 小时前
如何使用 Java 和 Jsoup 解析 HTML
大数据·开发语言·数据库·python·scrapy
如何原谅奋力过但无声2 小时前
现代化Python工具:uv、Ruff、Pyright、Rich(只讲重点版)
vscode·python·uv
Logintern092 小时前
DeepAgents 主-子 Agent 的底层实现逻辑完全基于 LangGraph 的图机制
python
码云骑士3 小时前
97-Milvus从零到生产-Standalone-vs-Cluster-索引选择-分片监控扩容
python·milvus
accept 99%3 小时前
python版提取 PDF 的常用第三方库与工具
开发语言·python·pdf