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)
相关推荐
线上放牧人4 分钟前
Windows删除图标缓存
windows·python·pyqt
qq_54702617932 分钟前
Python 变量和简单数据类型
python
Koi慢热33 分钟前
DayDayMap学术社区体验:卫星网络测绘专题用下来怎么样
网络·人工智能·windows·web安全·网络安全
web守墓人2 小时前
【goed/ui】自定义组件设计思想篇
linux·windows·ui·golang
智搜广告2 小时前
智搜广告:科技行业AI回答优化公司如何破局
大数据·python·elasticsearch·geo
IpdataCloud2 小时前
AI智能体调用工具怎么核验来源IP?归属地、网络类型与代理风险识别(含Python代码)
数据库·python·tcp/ip
2601_966949653 小时前
只拿到股票代码还不够:量化程序到底还需要哪些标的信息?——从数据建模开始理解股票元数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
蒸鱼Yuzheng3 小时前
Python 游戏测试开发怎么准备:日志解析、接口校验、并发与可维护性
自动化测试·python·测试开发·面试题·游戏测试
Ivanqhz3 小时前
BM1688 双核架构
python·深度学习·神经网络·cnn·mlir
Java后端的Ai之路3 小时前
Python进阶探索17 - Python中的深拷贝与浅拷贝
人工智能·python·ai·浅拷贝·深拷贝