【发布时间】:2019-02-07 19:56:27
【问题描述】:
我有一个程序,我正在读取 JSON 文件,并根据文件中指定的参数执行一些 SQL。
load_json_file()
方法首先将 json 文件加载到 Python 对象(此处未显示但可以正常工作) 问题在于这里的代码:
class TestAutomation:
def __init__(self):
self.load_json_file()
# connect to Teradata and load session to be used for execution
def connection(self):
con = self.load_json_file()
cfg_dsn = con['config']['dsn']
cfg_usr = con['config']['username']
cfg_pwd = con['config']['password']
udaExec = teradata.UdaExec(appName="DataAnalysis", version="1.0", logConsole=False)
session = udaExec.connect(method="odbc", dsn=cfg_dsn, username=cfg_usr, password=cfg_pwd)
return session
init_ 方法首先加载 JSON 文件,然后将其存储在“con”中。我收到一条错误消息:
cfg_dsn = con['config']['dsn']
E TypeError: 'NoneType' object is not subscriptable
JSON 文件如下所示:
{
"config":{
"src":"C:/Dev\\path",
"dsn":"XYZ",
"sheet_name":"test",
"out_file_prefix":"C:/Dev\\test\\OutputFile_",
"password":"pw123",
"username":"user123",
"start_table":"11",
"end_table":"26",
"skip_table":"1,13,17",
"spot_check_table":"77"
}
}
load_json_file() 是这样定义的:
def load_json_file(self):
if os.path.isfile(os.path.dirname(os.path.realpath(sys.argv[0])) + '\dwconfig.json'):
with open('dwconfig.json') as json_data_file:
cfg_data = json.load(json_data_file)
return cfg_data
我看到错误的任何想法?
【问题讨论】:
-
请提供minimal reproducible example。看看
load_json_file是如何定义的会特别有用。 -
要么
con为无,要么con['config']为无。 -
显然 con 是 None,否则你会得到一个 KeyError (tested)。
Not subscriptable表示您不能在其上“索引”(使用 object[index])符号;你不能这样迭代。 -
如果文件名不存在(或不可读),
load_json_file()将返回 None。 -
正如 John Gordon 指出的那样,您不会处理
os.path.isfile为假的情况。如果一个函数没有返回任何东西,它实际上返回了None。