Brendan Brendan - 2 months ago 20
JSON Question

Run Code If A JSON Key Exists

I am using Python 3 on Windows 10 64bit.

I am trying to return the key "class" of every key in

classes
. I was able to do this with the following function. I can not figure out how to do it only when the key
classes
exists because it will not always exist in my JSON files.

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

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