代码之家  ›  专栏  ›  技术社区  ›  JD2775

python错误:将json加载到变量中时,非类型对象不可订阅

  •  0
  • JD2775  · 技术社区  · 7 年前

    我有一个程序,我在其中读取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
    

    这个 伊尼特 方法首先加载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
    

    你知道我为什么看到这个错误吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Jean-François Fabre    7 年前

    问题是您正在检查配置文件是否存在,然后读取它。

    如果没有,则函数返回 None . 这在很多方面都是错误的,因为 os.path.realpath(sys.argv[0]) 可以返回不正确的值,例如,如果命令仅使用通过系统路径找到的基名称运行( $0 返回bash中的完整路径,但不返回python或c中的完整路径)。

    这不是获取当前命令目录的方法。

    (加上之后你要做的 with open('dwconfig.json') as json_data_file: 它现在是文件名,没有完整路径,再次出错)

    我将跳过此测试,但正确计算配置文件路径。如果它不存在,让程序崩溃而不是返回 没有 以后会崩溃的。

    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
    
        2
  •  0
  •   Grady Player    7 年前

    所以… cfg_dsn = con['config']['dsn']

    里面的东西设为“无”

    你可以安全地写下来

    (con or {}).get('config',{}).get('dsn')

    或者让你的数据正确。