0

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".

2
  • 1
    Your check is wrong. if not data['products']: should be if data['products']:. You could also check: if any(data['products']): Commented Oct 16, 2017 at 10:44
  • Yes, the second attempt should work if you fix the condition. Commented Oct 16, 2017 at 10:49

3 Answers 3

1

You don't have to do this check at all.

You can simply iterate over the empty list. It won't do anything if there is nothing.:

data = json.loads(r.text)
for key in data['products']:
    print(key['info']['sku'])

EDIT

If you want to stop your iteration:

if not data['products']:
    break
for key in data['products']:
    print(key['info']['sku']) 
Sign up to request clarification or add additional context in comments.

3 Comments

Except this code is in a while loop to iterate through page 1, 2, etc so I need to check whether this is the last record as the API returns no products.
The if not data[‘products’]: will always be true as there is always products, just it’s an empty list when there aren’t any.
Try to execute this on your interpreter: if not []: print('this list is empty')
0
if 'info' in r.text:

Also works. Which option is best practice and I will mark as correct?

Comments

0

check its len, like this:

data = json.loads(r.text)

print(data)

if len(data['products']) > 0:
    print("something")
    for key in data['products']:
        print(key['info']['sku'])

else:
    print("nothing")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.