1

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.

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thx i like this answer.
1

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']

Comments

1

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

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

Comments

1

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'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.