Conditional statement to check if a JSON key is nu

2019-08-05 04:03发布

问题:

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


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.

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)

Example json_data:

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

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?

回答1:

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

or defensively

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

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