【问题标题】:Python error: Nonetype object not subscriptable, when loading JSON into variablesPython 错误:将 JSON 加载到变量中时,Nonetype 对象不可下标
【发布时间】: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

标签: python json


【解决方案1】:

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

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

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

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

我会跳过这个测试,但会正确计算配置文件路径。如果它不存在,让程序崩溃而不是返回稍后会崩溃的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

【讨论】:

  • 谢谢,问题似乎已经解决。这很奇怪,我有另一个函数,我正在将 JSON 文件的不同部分读入变量,它工作正常。不过,这可能是一个更好的方法
【解决方案2】:

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

里面的东西设置为无

你可以安全地写它

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

或使您的数据正确。

【讨论】:

  • 谢谢格雷迪。我不确定为什么它设置为无。您可以在上面的 JSON 文件中看到 dsn 有一个值。
  • 注销:self.load_json_file()
猜你喜欢
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多