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

15,017

Solution 1

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

Solution 2

If you have the JSON in a string then just use Python's json.loads() function to load JSON parse the JSON and load its contents into your namespace by binding it to some local name

Example:

#!/bin/env python
import json
some_json = '''{ "hosts":  {
         "example1.lab.com" : ["mysql", "apache"],
         "example2.lab.com" : ["sqlite", "nmap"],
         "example3.lab.com" : ["vim", "bind9"]
         }
}'''
some_stuff = json.loads(some_json)
print some_stuff['hosts'].keys()

---> [u'example1.lab.com', u'example3.lab.com', u'example2.lab.com']

As shown you then access the contents of some_stuff just as you would any other Python dictionary ... all the top level variable declaration/assignments which were serialized (encoded) in the JSON will be keys in that dictionary.

If the JSON contents are in a file you can open it like any other file in Python and pass the file object's name to the json.load() function:

#!/bin/python
import json

with open("some_file.json") as f:
    some_stuff = json.load(f)

print ' '.join(some_stuff.keys())
Share:
15,017

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin over 1 year

    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.

    • falsetru
      falsetru over 10 years
      Given json is in invalid format.