2017-03-05 89 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