首页 > 解决方案 > 如何获取 json 对象中的键值(Python)

问题描述

这是我的 json :

{'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}

我想获取名称的所有值的列表。
我在 python 中的代码应该是什么

标签: pythonjson

解决方案


d.values给出所有的值,然后你可以得到name每个值的属性。

d = {'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}

[i['name'] for i in d.values()]
['poulami', 'test']

另请注意,d.values返回生成器而不是列表,以便转换为列表使用list(d.values())


推荐阅读