gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:11:32 26 4
gpt4 key购买 nike

我有一个 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 slice, not str

最佳答案

使用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]

关于Python - 获取JSON中字段的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42606695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com