简体   繁体   English

如何获取 json 对象中的键值(Python)

[英]How to get key values in a json object(Python)

This is my json :这是我的 json :

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

I want to get a list of all the values of name.我想获得 name 的所有值的列表。
What should be my code in python我在 python 中的代码应该是什么

d.values gives all the values, then you can get the attribute name of each value. 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']

Also note that d.values returns a generator and not a list so to convert to list use list(d.values())另请注意, d.values返回生成器而不是列表,以便转换为列表使用list(d.values())

That is not JSON format.那不是 JSON 格式。 It is a Python Dictionary.它是一个 Python 词典。

Iterate over the values of the dictionary( d.values() ) and get the name from each item.迭代字典( d.values() )的值并从每个项目中获取name

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

names_list = []

for i in d.values():
    names_list.append(i['name'])
names_list = ['poulami', 'test']

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

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