Python错误:将JSON加载到变量时,非类型对象不可下标
我有一个程序,我在其中读取JSON文件,并根据文件中指定的参数执行一些SQL。Python错误:将JSON加载到变量时,非类型对象不可下标,python,json,Python,Json,我有一个程序,我在其中读取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 conne
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"
}
}
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
load_json_file()的定义如下:
{
"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"
}
}
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
知道我为什么会看到这个错误吗?所以
cfg_dsn=con['config']['dsn']
其中的某些内容设置为“无”
你可以很安全地这样写
(con或{}).get('config',{}).get('dsn')
或者使您的数据正确。问题是您正在检查配置文件是否存在,然后读取它 如果没有,则函数返回
None
。这在许多方面都是错误的,因为os.path.realpath(sys.argv[0])
可能返回错误的值,例如,如果命令仅使用通过系统路径找到的基名称运行($0
在bash中返回完整路径,但在python或C中不返回)
这不是获取当前命令目录的方式
(加上之后您将使用open('dwconfig.json')作为json_data_文件执行:
现在是文件名,没有完整路径,再次出错)
我会跳过这个测试,但会正确地计算配置文件路径。如果它不存在,让程序崩溃,而不是返回稍后将崩溃的None
def load_json_file(self):
with open(os.path.join(os.path.dirname(__file__),'dwconfig.json')) as json_data_file:
cfg_data = json.load(json_data_file)
return cfg_data
请提供一份报告。查看如何定义
load\u json\u file
将特别有用。要么con
为None,要么con['config']
为None。显然,con为None,否则您将得到一个keyrerror(已测试)<代码>不可下标表示不能“索引”(使用对象[索引])符号;如果文件名不存在(或不可读),load\u json\u file()
将返回None。正如John Gordon指出的,您不会处理os.path.isfile
为false的情况。如果函数不返回任何内容,它实际上返回None
。谢谢Grady。我不知道为什么设置为“无”。您可以在上面的JSON文件中看到dsn有一个值。注销:self.load_JSON_file()谢谢,这似乎解决了问题。奇怪的是,我有另一个函数,我将JSON文件的不同部分读入变量,它工作得很好。这可能是一个更好的方法