Brendan Brendan - 3 years ago 178
JSON Question

If JSON Key Exists Else

Hope you are having a great day! I am trying to return

{'green color','road','street','yellow color'}
which I was able to do with this function in python 3 but I only want it to return it if the key "CLASSES" exists in the dictionary "json_data". When I run the function with the following JSON code it works but when I run other code that does not have a key "CLASSES" I just want it to return None. How do I do that? When I give it other json data right now it shows the image at the bottom.

Here is the code:

def parse_classes(json_data):
lst = list()
for classes in json_data['images'][0]['classifiers'][0]:
for item in json_data['images'][0]['classifiers'][0]['classes']:
class1 = item['class']
lst.append(class1)

else:
print("")
lst = set(lst)
return(lst)


Here is the json:

{
"custom_classes": 0,
"images": [
{
"classifiers": [
{
"classes": [
{
"class": "street",
"score": 0.846,
"type_hierarchy": "/road/street"
},
{
"class": "road",
"score": 0.85
},
{
"class": "yellow color",
"score": 0.872
},
{
"class": "green color",
"score": 0.702
}
],
"classifier_id": "default",
"name": "default"
}
],
"image": "images/parisstreets/paris-streets-1.jpg"
}
],
"images_processed": 1
}


Image:

enter image description here

Thank you!

UPDATE:
This is a followup question to Retrieve Multiple JSON Items Python

UPDATE #2
Here is the code for when it throws the error:

{
"custom_classes": 3,
"images": [
{
"classifiers": [],
"image": "datasets/dogs/testing/basset/Image11.jpg"
}
],
"images_processed": 1
}

cmd cmd
Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download