使用Python 3检查JSON密钥是否为空的条件语句 [英] Conditional statement to check if a JSON key is null with Python 3

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

问题描述

已对此问题进行了更新,以澄清问题,以便将来可以更好地帮助其他人.

This has been updated to clarify the question so it can better help others in the future.

我正在尝试使用if语句来测试键classes是否在使用Python的JSON结构中存在.使用Python检查密钥是否存在于JSON结构中.我可以获取密钥,但需要帮助来确定应该检查的条件是什么.

I am attempting to use an if statement to test if the key classes exists in a JSON structure using Python. to check if a key exists in a JSON structure using Python. I am able to get the key but need help finding out what the condition should be to check if it exists.

使用以下代码,当JSON结构中存在键class时,我能够成功返回它的值:

I successfully was able to return the value of the key class when it is exsits in the JSON structure using the following code:

#Parameter: json_data - The JSON structure it is checking
def parse_classes(json_data):
    lst = list()
    if('classes' is in json_data['images'][0]['classifiers'][0]): #This doesn't work
        for item in json_data['images'][0]['classifiers'][0]['classes']: 
            lst.append(item['class'])
    else:
        lst = None

    return(lst)


示例json_data:


Example json_data:

{"images": ["classifiers": ["classes": ["class": "street"]]]}


我的问题似乎在第4行上,问题似乎是条件语句不正确.我需要对if语句进行哪些更改才能使其正常工作?


My issue seems to be on line 4 and the issue seems to be that the conditional statement is incorrect. What do I need to change about the if-statement to make it work correctly?

推荐答案

我认为您的意思是if而不是for:

I think you mean if instead of for:

def parse_classes(json_data):
    lst = set()
    if 'classes' in json_data['images'][0]['classifiers'][0]:
        for item in json_data['images'][0]['classifiers'][0]['classes']:
            lst.add(item['class'])
    else:
        print("")
    return lst

或防守上

def parse_classes(json_data):
    lst = set()
    if (json_data.get('images')
            and json_data['images'][0].get('classifiers')
            and json_data['images'][0]['classifiers'][0].get('classes')):
        for item in json_data['images'][0]['classifiers'][0].get('classes', []):
            lst.add(item['class'])
    return lst if lst else None

如果要所有images中的所有classifiers中的所有class

if you want all class in all classifiers in all images

def parse_classes(json_data):
    lst = set()
    for image in json_data.get('images', []):
        for classifier in image.get('classifiers', []):
            for item in classifier.get('classes', []):
                lst.add(item['class'])
    return lst if lst else None

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

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