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

标签 python json

我有一个 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/

相关文章:

python - 本地导入类的 PyCharm/Python 文档字符串返回类型提示

python - 多线程无锁将item追加到同一个列表中是否正确?

python - 如何构建Python模块以使其既可扩展又可测试?

jquery - 使用新属性扩展 json 模型

php - Laravel 5.2 : Redraw DataTable is not working But ajax. 重新加载()正在工作

json - Bash 和 jq - 查找变量中包含的键并更改其值

PHP - json_encode(string, JSON_UNESCAPED_UNICODE) 不转义捷克字符

python ,被杀了?

python - `with` 中 `concurrent.futures` 的功能

javascript - 使用 Angular JS 循环遍历 JSON 中的数组