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

2024-09-30 01:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下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"]将打印出第一个元素,但宿主可以位于任何位置


Tags: namenoneportlocalstatustagsgroupaddr
3条回答

这也许是个骗局,因为在引擎盖下它会循环:

print myjson["Members"][myjson["Members"].index('myhost1.mydomain.local')]["Tags"]

您可以将数组转换为从主机到数据的字典。然后,你可以直接根据你要找的主机地址

# Create the dictionary from name->row
host_dict = dict((row['Name'], row) for row in myjson['Members'])

tags = host_dict['myhost1.mydomain.local']['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

相关问题 更多 >

    热门问题