You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python去除JSON字符串多余字符及处理None类型报错求助

解决JSON处理中None值调用strip的AttributeError问题

首先咱们来拆解你遇到的问题:

  • 错误提示AttributeError: 'NoneType' object has no attribute 'strip',确实是因为部分IdealValue的值为null(对应Python里的None),而None没有strip方法,直接调用就会触发报错。
  • 另外还有个隐藏坑:你定义的data是JSON字符串,不是Python字典,直接用data['attributeInfo']会先触发TypeError,得先把它解析成Python可操作的对象才行。

修正后的完整代码

import json

# 原始JSON字符串
data = "{ \"attributeInfo\":[ { \"AttributeName\":\"s:Density\", \"Weight\":\"s:0.2\", \"Preference\":\"s:Closer to a target is better\", \"IdealValue\":\"s:7850\" }, { \"AttributeName\":\"s:Endurance Strength\", \"Weight\":\"s:0.2\", \"Preference\":\"s:Larger is better\", \"IdealValue\":null }, { \"AttributeName\":\"s:Modulus of Elasticity\", \"Weight\":\"s:0.2\", \"Preference\":\"s:Larger is better\", \"IdealValue\":null }, { \"AttributeName\":\"s:Cost\", \"Weight\":\"s:0.2\", \"Preference\":\"s:Smaller is better\", \"IdealValue\":null } ]}"

# 先把JSON字符串解析成Python字典
parsed_data = json.loads(data)
tmp = []

for item in parsed_data['attributeInfo']:
    nDict = {}
    for key, value in item.items():
        # 处理键:用lstrip精准去除开头的"s:",避免strip误删其他位置的s/:
        cleaned_key = key.lstrip('s:')
        # 处理值:非None的字符串才做strip操作,None直接保留
        cleaned_value = value.lstrip('s:') if value is not None else value
        nDict[cleaned_key] = cleaned_value
    tmp.append(nDict)

# 打印处理后的结果
print(tmp)

关键修复点说明

  • 解析JSON字符串:用json.loads()把原始JSON字符串转换成Python字典/列表,这是操作JSON数据的基础步骤,避免直接操作字符串导致的类型错误。
  • None值安全处理:在调用strip前先判断value is not None,确保只有字符串类型的 value 才执行去除操作,完美规避None类型的属性错误。
  • 精准去除前缀:用lstrip('s:')代替strip('s:'),因为你只需要去掉开头的s:,而strip会去除两端所有匹配的字符,可能会误改键值内容。
  • 避免覆盖内置类型:不要用dict作为变量名,它会覆盖Python内置的dict类型,换成item这类更规范的名称。

运行结果示例

处理后的每个字典都会去掉键和值开头的s:,同时保留IdealValue的None值:

[
    {'AttributeName': 'Density', 'Weight': '0.2', 'Preference': 'Closer to a target is better', 'IdealValue': '7850'},
    {'AttributeName': 'Endurance Strength', 'Weight': '0.2', 'Preference': 'Larger is better', 'IdealValue': None},
    {'AttributeName': 'Modulus of Elasticity', 'Weight': '0.2', 'Preference': 'Larger is better', 'IdealValue': None},
    {'AttributeName': 'Cost', 'Weight': '0.2', 'Preference': 'Smaller is better', 'IdealValue': None}
]

内容的提问来源于stack exchange,提问作者Shane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:43:19