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)
相关推荐
疯狂成瘾者1 小时前
语义分块提升RAG检索精度
python
小陈工3 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
A__tao7 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
研究点啥好呢7 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
航Hang*7 小时前
Windows Server 配置与管理——第3章:文件系统管理
运维·服务器·windows·vmware
迷藏4947 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
明日清晨8 小时前
python扫码登录dy
开发语言·python
bazhange8 小时前
python如何像matlab一样使用向量化替代for循环
开发语言·python·matlab
人工干智能8 小时前
科普:python中你写的模块找不到了——`ModuleNotFoundError`
服务器·python
unicrom_深圳市由你创科技8 小时前
做虚拟示波器这种实时波形显示的上位机,用什么语言?
c++·python·c#