I need to return a bunch of SKUs from a JSON API response but sometimes it's "empty":
{'products': [], 'request_speed': 0.0015690326690674}
This code works when there are products but raises an IndexError when there are no products:
data = json.loads(r.text)
print(data)
if not data['products'][0]:
print("something")
for key in data['products']:
print(key['info']['sku'])
else:
print("nothing")
And this always has "something" because there is always a "products" [] in the response:
data = json.loads(r.text)
print(data)
if not data['products']:
print("something")
for key in data['products']:
print(key['info']['sku'])
else:
print("nothing")
I know I could add a try/except to the first example but it seems a round the houses way of achieving something.
Is there a more shorthand way of achieving this? I did think:
if 'info' in data['products']:
Was the pythonic way but this always returns "nothing".
if not data['products']:should beif data['products']:. You could also check:if any(data['products']):