首页 > 解决方案 > 从 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'

请让我知道如何处理此错误,这是由于某些值中存在空值。

标签: jsonpython-3.xdictionarykey-value

解决方案


如果您的data变量是 JSON 有效值,您可以使用jsonPython 的模块对其进行解析。

您的错误来自键null中存在的值IdealValue

nDict = {key.strip('s:'): value.strip('s:') for key, value in dict.items() if value is not None}应该可以解决问题,但IdealValue如果它的值是null

最好的,


推荐阅读