简体   繁体   中英

AttributeError: 'NoneType' object has no attribute 'get' while on loop

I know this is an attribute error that is caused because of trying to access a property that is not defined on the

So basically I am parsing a JSON response returned by an API.

the response looks like this.

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

which I am looping the x = response.json() object and trying to access as,

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

which works on the testing with the interpreter manually

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

but when accessed the same inside a class function, it raises attribute error. What am I doing wrong?

The error is only raised when the method is called progmatically when the value of someProperty is null.

update

it is how I am using inside a class.

class SomeClass(object):

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

    def save():
        pass

Now the usage,

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

You are forgetting the case where someProperty exists, but is set to None . You included that case in your input JSON:

{
    "someProperty":null
}

Here the key exists , and its value is set to None (the Python equivalent for null in JSON). That value is then returned by dict.get() , and None doesn't have a .pop() method.

Demo:

>>> 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() only returns the default if the key does not exist. In the above example, "someProperty" exists, so it's value is returned.

I'd replace any falsey value with an empty dictionary:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM