gpt4 book ai didi

python - 在 Python 中,如何获取已知键的 JSON 值

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:30 25 4
gpt4 key购买 nike

假设我有以下 JSON 格式的输出。我想为特定主机名提取 tags ,有没有办法在不循环的情况下做到这一点?我想获取 myhost1.mydomain.local 的标签 我该如何实现?

{'Members': [{'Addr': None,
'Name': 'myhost1.mydomain.local',
'Port': 7946,
'Status': 'alive',
'Tags': {'cluster_group': 'even',
'datacenter': 'mco',
'environment_id': 'mco-sc'}},
{'Addr': None,
'Name': 'myhost2.mydomain.local',
'Port': 7946,
'Status': 'alive',
'Tags': {'cluster_group': 'odd',
'datacenter': 'mco',
'environment_id': 'mco-sf'}}]}

print myjson["Members"][0]["Tags"] 将打印出第一个元素,但主机可以位于任何位置。

最佳答案

使用过滤器?

entry = filter(lambda x: x['Name']=='myhost1.mydomain.local', myjson['Members'])
# this will give you a sequence of zero or more elements

# if you want to return first element or None without raising exception, you can do something like:
return entry[0]['Tags'] if len(entry) else None

关于python - 在 Python 中,如何获取已知键的 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441517/

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