Python获取JSON中字段的所有值

2024-05-10 14:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个geoJSON文件,我想提取子字段中所有可能的值。因此,对于两个项目长的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


Tags: 文件项目jsondatageojsonpropertiesbelist
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]

您可以使用list comprehension来收集所需的数据。在您的示例中:

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

更新了:很抱歉,@DeepSpace给出的答案中有更好的/pythonic代码,只需迭代data['features'],而不是range(len(data))

相关问题 更多 >