gpt4 book ai didi

python - 如何使用 Python 按名称引用 json 数组元素?

转载 作者:行者123 更新时间:2023-11-30 23:06:21 25 4
gpt4 key购买 nike

在此 json 数组中:

json_string=[{"Id": "report","Value": "3001"},{"Id": "user","Value": "user123"}]

如果我传入user,如何取回user123

当我尝试这样做时:

content = json.loads(json_string) 
content['user']

我收到一条错误,提示您必须使用整数来引用元素。

我是 Python 新手。

谢谢!

最佳答案

content 是一个列表,因此您应该首先按索引获取元素:

>>> content[1]['Value']
'user123'

>>> for d in content:
... if 'user' in d.values():
... print d['Value']
'user123'

假设 user 始终映射到 Id:

>>> for d in content:
... if d['Id'] == 'user':
... print d['Value']

一类轮:

 >>> [d['Value'] for d in content if d['Id'] == 'user'][0]
'user123'

关于python - 如何使用 Python 按名称引用 json 数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704823/

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