pythonjsonpython-2.7

Checking if JSON key is empty


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


Solution

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