简体   繁体   English

Python - 获取 JSON 中字段的所有值

[英]Python - Get all values of field in JSON

I have a geoJSON file, and I'd like to extract all the possible values in a subfield.我有一个 geoJSON 文件,我想提取子字段中的所有可能值。 So for a two items long json it would be like this:因此,对于两个项目长的 json,它将是这样的:

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

I'd like to return [38, 51] .我想返回[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但它不起作用,因为类型错误TypeError: list indices must be integers or slices, not str

Use a for loop:使用for循环:

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]

You can use list comprehension to collect the data you want.您可以使用list comprehension来收集您想要的数据。 In your example its:在您的示例中:

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

Updated : Sorry, the better/pythonic code is in the answer gave by @DeepSpace, just iterate data['features'] , not range(len(data))更新:对不起,更好的/pythonic 代码在@DeepSpace 给出的答案中,只是迭代data['features'] ,而不是range(len(data))

[i['properties']['cellId'] for i in data['features']]

以@DeepSpace 的评论,使用这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM