AttributeError:' NoneType'对象没有属性' get'在循环中

时间:2017-08-19 15:04:05

标签: python json dictionary attributeerror pop

我知道这是由于尝试访问未在

上定义的属性而导致的属性错误

所以基本上我正在解析API返回的JSON响应。

响应看起来像这样。

{
    "someProperty": {
         "value": 123
     }
},
{
    "someProperty":null
},

我正在循环x = response.json()对象并尝试访问,

x.get('someProperty', {}).pop('value', 0)

可以手动使用解释器进行测试

In[2]: x = {1:2, 2:34}
In[3]: x.get('someProperty', {}).pop('value', 0)
Out[3]: 0

但是当在类函数中访问它时,它会引发属性错误。我做错了什么?

只有在someProperty的值为空时以预定方式调用方法时才会引发错误。

更新

这就是我在课堂上使用的方式。

class SomeClass(object):

    def __init__(self, **kwargs):
        self.value = kwargs.get('someProperty', {}).pop('value', 0)

    def save():
        pass

现在用法,

x = response.json()
for num, i in enumerate(x):
    j = SomeClass(**i)
    j.save()

1 个答案:

答案 0 :(得分:2)

您忘记了someProperty存在的情况,但设置为None。您在输入JSON中包含了这种情况:

{
    "someProperty":null
}

此处键存在,其值设置为None(JSON中null的Python等价物)。然后,dict.get()会返回该值,而None没有.pop()方法。

演示:

>>> import json
>>> json.loads('{"someProperty": null}')
{'someProperty': None}
>>> x = json.loads('{"someProperty": null}')
>>> print(x.get("someProperty", 'default ignored, there is a value!'))
None
如果密钥不存在,

dict.get()仅返回默认值。在上面的示例中,"someProperty"存在,因此会返回它的值。

我用空字典替换任何falsey值:

# value could be None, or key could be missing; replace both with {}
property = kwargs.get('someProperty') or {}  
self.value = property.pop('value', 0)