python - extract a specific key / value from the json file by a variable

advertisements

a bit new to python and json. i have this json file:

{ "hosts":  {
             "example1.lab.com" : ["mysql", "apache"],
             "example2.lab.com" : ["sqlite", "nmap"],
             "example3.lab.com" : ["vim", "bind9"]
             }
}

what i want to do is use the hostname variable and extract the values of each hostname. its a bit hard to explain but im using saltstack, which already iterates over hosts and i want it to be able to extract each host's values from the json file using the hostname variable.

hope im understood.

thanks o.


You could do something along these lines:

import json

j='''{ "hosts":  {
             "example1.lab.com" : ["mysql", "apache"],
             "example2.lab.com" : ["sqlite", "nmap"],
             "example3.lab.com" : ["vim", "bind9"]
             }
}'''

specific_key='example2'

found=False
for key,di in json.loads(j).iteritems():    # items on Py 3k
    for k,v in di.items():
        if k.startswith(specific_key):
            found=True
            print k,v
            break
    if found:
        break

Or, you could do:

def pairs(args):
    for arg in args:
        if arg[0].startswith(specific_key):
            k,v=arg
            print k,v

json.loads(j,object_pairs_hook=pairs)

Either case, prints:

example2.lab.com [u'sqlite', u'nmap']