sdot257
sdot257

Reputation: 10366

In Python, how can I get JSON value for a known key

Let's say I have the following output in JSON. I want to pull tags for a particular hostname, is there a way to do it without looping through it? I want to grab the tags for myhost1.mydomain.local How can I accomplish this?

{'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"] would print out the first element but the host could be in any position.

Upvotes: 1

Views: 46

Answers (4)

marw
marw

Reputation: 3119

Like this:

[i['Tags'] for i in a['Members'] if i['Name']=='myhost2.mydomain.local']

You get:

[{'cluster_group': 'odd', 'datacenter': 'mco', 'environment_id': 'mco-sf'}]

Upvotes: 1

Jay Atkinson
Jay Atkinson

Reputation: 3287

This maybe a cheat, because under the hood it loops:

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

Upvotes: 1

Strikeskids
Strikeskids

Reputation: 4052

You could turn your array into a dictionary from host to data. Then, you can directly address based on the host your a looking for

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

tags = host_dict['myhost1.mydomain.local']['Tags']

Upvotes: 1

Ashalynd
Ashalynd

Reputation: 12563

Using filter?

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

Upvotes: 1

Related Questions