检查JSON密钥是否为空 [英] Checking if JSON key is empty

查看:197
本文介绍了检查JSON密钥是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够检查JSON密钥是否为空,然后根据结果退出脚本.

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

我有以下JSON:

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

如果"results"键为空(如上所述),我希望脚本以返回码0退出,否则它将返回1.

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.

我尝试过

import json, sys

obj=json.load(sys.stdin)

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

但这会产生:

IndexError: list index out of range

推荐答案

同时检查密钥的存在及其长度:

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)

这篇关于检查JSON密钥是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆