Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if JSON key is empty [closed]

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

like image 820
Adam Chance Avatar asked Jun 07 '26 02:06

Adam Chance


1 Answers

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)
like image 57
Thiago Rossener Avatar answered Jun 10 '26 07:06

Thiago Rossener



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!