首页 > 解决方案 > Python 3 将 json 值读取为元组

问题描述

我为我的 python 脚本创建了一个文件参数。我的想法是从 JSON 文件中读取这些参数,然后在需要的地方执行。

这是示例文件:

{
"configfiles": [
        {
            "log": "/home/ubuntu/scripts/mtm-etl/etl-process-log",
            "connection":"/home/ubuntu/scripts/mtm-etl/etlconfig/mtm-connection",
            "query_redshift_library":"/home/ubuntu/scripts/mtm-etl/etlconfig/query_redshift_library"
        }
    ]
}

好的,现在我假装在我的脚本中读取这些键值,然后将它们分配给一个变量,这是我的代码:

 with open('etl-parameters','r') as userinfo:
        param = json.load(userinfo)

    for param,extraction in param.items():
        if ("ETL" in param):
            for item in extraction:
                process = item['etl-process']
                stored_query = item['stored-query']
        elif( "configfiles"  in param):
            for item in extraction:
                logfile = item['log'],
                connectionfile = item['connection'],
                query_redshift_library = item['query_redshift_library']

我的问题在于,elif因为一个变量被分配了正确的数据类型作为字符串,但由于某种原因,变量logfile分配connectionfile了一个元组。我在调试中赶上了这一点:

在此处输入图像描述 在此处输入图像描述

感谢您的反馈

谢谢

标签: pythonjsonpython-3.x

解决方案


该错误是由那里的多余逗号引起的:

            logfile = item['log'],
            connectionfile = item['connection'],

删除它们,您将获得变量作为 str:

            logfile = item['log']
            connectionfile = item['connection']

至于为什么会这样工作:python 解释以逗号结尾的行,就好像您确实将单个元素元组分配给变量(实际上不需要括号),就像在这个更简单的示例中一样:

>>> a = 5,
>>> print(a)
(5,)
>>> print(str(type(a)))
<class 'tuple'>
>>>

推荐阅读