Brendan Brendan - 4 months ago 27
JSON Question

Retreive JSON Keys In Python

I set the following JSON code as variable

json_data
in Python 3.

JSON CODE:

{
"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
}


I would like the output to be the following which is a dictionary of every key called
class
.

{'street','road','yellow color','green color'}


Here is the code I tried:

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


Here is the traceback that I am getting:

TypeError: list indices must be integers or slices, not str

Answer Source

The first issue is that classifiers is also a list, so you need an additional index to get at classes. This will work:

for item in json_data['images'][0]['classifiers'][0]['classes']:

Second, you want the result as a set not a list, so you can do: return set(lst). Note that sets are unordered, so don't expect the ordering of items to match that of the list.