2017-03-05 43 views
0

我有一個geoJSON文件,並且想要提取子字段中的所有可能值。因此,對於一兩個項目長JSON這將是這樣的:Python - 在JSON中獲取字段的所有值

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

我想退貨[38, 51]。可能嗎?我試圖

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

,但它不工作,因爲TypeError: list indices must be integers or slices, not str

回答

2

使用for循環:

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

或者,如果你想存儲這些,而不是隻打印其個人使用列表理解:

cell_ids = [element['properties']['cellId'] for element in data['features']] 
print(cell_ids) 
# [38, 51] 
0

您可以使用list comprehension co選擇你想要的數據。在你的榜樣的:

[data['features'][i]['properties']['cellId'] for i in range(len(data))] 

更新:對不起,更好的/ Python的代碼是在回答了由@DeepSpace,只是重複data['features'],不range(len(data))

+1

你應該使用迭代相當的Python的方式而不是'對於範圍內的我(len(..))',並且你還應該遍歷'data ['features']'而不是'data'。 – DeepSpace

+1

@DeepSpace,感謝您的友好提醒,我正在更新我的答案並投票支持你;-) – shizhz