json - 从 json 字符串中删除多余的字符并处理无数据类型 Python
问题描述
我正在尝试从 json 字符串中删除“s:”。当我尝试从键值对中去除多余的字符时,我看到了错误,请帮忙。
代码:
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
}
]}"
tmp =[]
li = data['attributeInfo']
for j in range(len(li)):
dict = li[j]
nDict = {key.strip('s:'): value.strip('s:') for key, value in dict.items()}
tmp.append(nDict)
print(nDict)
错误:nDict = {key.strip('s:'): value.strip('s:') for key, value in dict.items()} AttributeError: 'NoneType' object has no attribute 'strip'
请让我知道如何处理此错误,这是由于某些值中存在空值。
解决方案
如果您的data
变量是 JSON 有效值,您可以使用json
Python 的模块对其进行解析。
您的错误来自键null
中存在的值IdealValue
。
nDict = {key.strip('s:'): value.strip('s:') for key, value in dict.items() if value is not None}
应该可以解决问题,但IdealValue
如果它的值是null
最好的,
推荐阅读
- html - 如何在 knockoutjs 中为背景颜色样式属性应用三元运算符?
- angular - RoamingSettings.saveAsync 仅在桌面上返回权限被拒绝错误
- python - 使用 Python 检测可用的网络适配器
- javascript - 如何按这些字符串的一部分对字符串进行排序?
- java - Java - 如何配置 log4j2.xml
- javascript - 如何使用用户支付的相同按钮将所选选项提交到 mysql
- monitoring - 避免在 Prometheus 中抓取重复/克隆/主从目标?
- javascript - 通过调用函数修复 Javascript 堆内存不足的奥秘
- flutter - Dart - 如何将函数作为参数传递
- sql - 如果存在更新,则查询从表中获取更新的记录,否则获取新记录