2

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?

9
  • for item in json_data['images'][0]['classifiers'][0]['classes']: shouldn't it be for item in classes ? Commented Jul 25, 2017 at 20:54
  • This is a follow-up question to stackoverflow.com/questions/45310791/… Commented Jul 25, 2017 at 20:56
  • you need to check len(json_data['images']) , then len(json_data['images'][0]['classifiers']) Commented Jul 25, 2017 at 20:57
  • you're screenshot doesn't match the code you posted (quotes vs no quotes for classes). I first edited it but cmd answer made me rollback. Commented Jul 25, 2017 at 20:57
  • It doesn't work, so how can it work with or without quotes? Commented Jul 25, 2017 at 21:00

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

10 Comments

Still says IndexError: List index out of range
It works for the json data you have given. Do you have the data for when this fails?
json_data['images'][0]['classifiers'][0] must be empty in one of the sub-lists. cannot reproduce
@cmd I added the code. With your second thing it still says list index out of range.
will need to see full error and/or data it errors on.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.