8

I'd like to be able to check if a JSON key is empty, then have the script exit depending on the result.

I have the following JSON:

{
    "changed": false,
    "results": []
}

If the "results" key is empty, as it is above, I want the script to exit with a return code of 0, otherwise it should return 1.

I've tried

import json, sys

obj=json.load(sys.stdin)

if obj["results"]=="":
    exit(0)
else:
    exit(1)

But this produces:

IndexError: list index out of range

4
  • if not 'results' in obj? Which I guess becomes sys.exit(int(not 'results' in obj)) - I'm a bit confused where the title of your question fits into this - so I'm not sure what answer you're really after. Commented Aug 3, 2017 at 10:50
  • 1
    The code you posted can't throw that exception. Please include a valid minimal reproducible example with full traceback. Commented Aug 3, 2017 at 10:54
  • And note that for the given JSON, obj['result'] will produce [], not "", so the condition fails. Commented Aug 3, 2017 at 10:56
  • Sorry, I confused it with another question that I was going to post, will update title Commented Aug 3, 2017 at 10:57

2 Answers 2

21

Check both, the key existence and its length:

import json, sys

obj=json.load(sys.stdin)

if not 'results' in obj or len(obj['results']) == 0:
    exit(0)
else:
    exit(1)
Sign up to request clarification or add additional context in comments.

3 Comments

if not obj.get('results'): would be far more concise. However, the question is unclear, as there is no list access in the question so the exception makes no sense.
Yes, you are right.
Thank you, this solution with @MartijnPieters modification works
1
import json, sys

obj=json.load(sys.stdin)

if len(obj["results"])==0:
    exit(0)
else:
    exit(1)

try using the length of obj["results"]

2 Comments

Where the key doesn't exist, you won't have an object to check the length against - so this will produce the same error as the OP is currently receiving.
@JonClements - that's exactly why I'm here... I keep running into that exact issue...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.