Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Get all values of field in JSON

Tags:

python

json

I have a geoJSON file, and I'd like to extract all the possible values in a subfield. So for a two items long json it would be like this:

data['features'][0]['properties']['cellId']
#returns 38
data['features'][1]['properties']['cellId']
#returns 51

I'd like to return [38, 51]. Is it possible? I tried

data['features'][0:]['properties']['cellId']

but it doesn't work, since TypeError: list indices must be integers or slices, not str

like image 943
lte__ Avatar asked Jan 04 '23 10:01

lte__


1 Answers

Use a for loop:

for element in data['features']:
    print(element['properties']['cellId'])

Or use list comprehension if you want to store these instead of just printing them individually:

cell_ids = [element['properties']['cellId'] for element in data['features']]
print(cell_ids)
# [38, 51]
like image 75
DeepSpace Avatar answered Jan 06 '23 23:01

DeepSpace