python - 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
解决方案
您需要遍历该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。
推荐阅读
- ios - CloudKit 记录 ID 不是唯一的
- javascript - Webpack - 如何使用异步功能导入脚本
- azure-pipelines - Devops 中的 AdvancedInstaller - 无法同步文件
- flutter - Flutter Hive 无法检索 Map{}
- java - 以下在play 2.8.* import javax.persistence.MappedSuperclass中无法解决;
- vega-lite - 如何按时间单位对数据进行分箱和计数
- c - 你能解释一下 printf 的返回值分配给变量的代码吗?
- sqlite - 无法使用带有两个按钮的烧瓶从 sqlite db 中删除记录
- java - 增强循环不打印我所期望的
- javascript - 使用 Papa Parse 将 JSON 导出为 CSV