首页 > 解决方案 > Creating a json parsing function with Python

问题描述

I have been trying to create a function to use as an importable tool for parsing json. here is my code I have so far

#json parser
def jsonimporter(file_path , env_to_return):
    import json
    a = open(file_path,"r") #opens and sets the file to read

    data = a.read()         #sets variable to read function
    print(data)

    json_data = json.loads(data) #loads the json data and stores it in json_data variable


    print(json_data)
    json_data.get(env_to_return)

    return json_data

What my issue is, is that when I call the function in another file it does not display the parsed json it just displays the json as a a dict in this form;

{u'Environments': [{u'Dev': [u'111', u'222']}, {u'Qa': [u'333', u'444']}, {u'prod': [u'555', u'666']}]}

The print statements you see are just me trying to double check my answers. Also I have passed the call the correct parameters as it prints out the parameters if I ask it too. Thank you for your help!

dev = jsonimporter("test2.json","dev")
# dosomething with value
print(value)

This is how I called the function

标签: python

解决方案


您需要遍历该Environments属性,使用您想要的键搜索字典。

def jsonimporter(file_path, key, env_to_return):
    import json
    with open(file_path,"r") as a:
        json_data = json.load(a)

    for d in json_data[key]:
        if env_to_return in d:
            return d[env_to_return]

dev = jsonimporter("test2.json", "Environments", "dev")
print(dev)

另请参阅如何从 JSON 中获取字符串对象而不是 Unicode?了解如何在 Python 2 中使用普通字符串而不是 Unicode 字符串获取 JSON。


推荐阅读