Как удалить / пропустить объект в Python - PullRequest
0 голосов
/ 17 апреля 2020

Я получаю данные от SOAP вызова API от поставщика и использую библиотеку Zeep. Данные class 'NoneType', которые невозможно перебрать. Моя задача - удалить / пропустить NoneType object.

Если я получаю ответ, содержащий некоторые значения, я могу его jsonify, однако, если ответ возвращает None - я не могу jsonify его или удалить его.

Например, Я передал два списка параметров и получил два ответа обратно, один из которых содержит данные, а другой - Нет. Мой код ниже:

# 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)

Таким образом, вывод выглядит следующим образом:

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

Я пытался:

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

Ошибка: TypeError: 'NoneType' object is not iterable

1 Ответ

1 голос
/ 17 апреля 2020

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

Это не работает, поскольку response_list имеет значение None, поэтому вы не можете перебрать его.

Попробуйте:

response_list = response_list or []

Или

if response_list is None:
    response_list = []

Или

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

Или

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