Search code examples
pythonjsoniterationnonetypezeep

How to remove/skip <class 'NoneType'> object in Python


I am receiving the data from SOAP API call from a vendor and using Zeep library. The data is class 'NoneType' that is impossible to iterate through. My task is to remove/skip the NoneType object.

If I receive a response that contains some values, I am able to jsonify it, however, if the response returns None - I can't jsonify it or remove it.

For instance, I passed two lists of parameters and received two responses back, one that contains the data, the other one is None. My code below:

# Making a SOAP call and save the response
response = client.service.GetOrders(**params[0])

# convert the response object to native Python data format
py_response = helpers.serialize_object(response)

# jsonify (list of dictionaries)
response_list = json.loads(json.dumps(py_response, indent=4, sort_keys=True, default=str))

print(type(response_list)) 
print(response_list)

So the output is the following:

<class 'list'> # successfully converted 
[{'AgentID': 0, 'AgentName': 'Not specified', 'CustomerID': 1127}] 
<class 'NoneType'> # was not converted 
None

I have tried:

clean_response_list = [x for x in response_list if x != None]

Error: TypeError: 'NoneType' object is not iterable


Solution

  • clean_response_list = [x for x in response_list if x != None]

    This doesn't work because response_list is None, so you can't iterate over it.

    Try:

    response_list = response_list or []
    

    Or

    if response_list is None:
        response_list = []
    

    Or

    if py_response is not None:
        response_list = json.loads(json.dumps(py_response, indent=4, sort_keys=True, default=str))
    else:
        response_list = []        
    

    Or

    if py_response:
        response_list = json.loads(json.dumps(py_response, indent=4, sort_keys=True, default=str))
    else:
        response_list = []