简体   繁体   English

python - 通过变量从json文件中提取特定的键/值

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

a bit new to python and json.对python和json有点新。 i have this json file:我有这个json文件:

{ "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.它有点难以解释,但我使用的是 saltstack,它已经在主机上迭代,我希望它能够使用主机名变量从 json 文件中提取每个主机的值。

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

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如果您在字符串中有 JSON,那么只需使用 Python 的json.loads()函数来加载 JSON 解析 JSON 并将其内容加载到您的命名空间中,方法是将其绑定到某个本地名称

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.如图所示,您可以像访问任何其他 Python 字典一样访问some_stuff的内容……所有在 JSON 中序列化(编码)的顶级变量声明/赋值都将是该字典中的键。

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:如果 JSON 内容在文件中,您可以像 Python 中的任何其他文件一样打开它,并将文件对象的名称传递给json.load()函数:

#!/bin/python
import json

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

print ' '.join(some_stuff.keys())

If the above json file is stored as 'samplefile.json', you can write following in python:如果上面的json文件存储为'samplefile.json',你可以在python中编写以下内容:

import json
f = open('samplefile.json')
data = json.load(f)

value1 = data['hosts']['example1.lab.com']
value2 = data['hosts']['example2.lab.com']
value3 = data['hosts']['example3.lab.com']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM