python3将json值作为tup读取

2024-10-03 09:17:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我为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"
        }
    ]
}

好的,现在我假装在脚本中读取for中的键和值,将它们分配给变量,然后,我的代码如下:

^{pr2}$

我的问题是在elif中,因为一个变量被指定了正确的数据类型作为字符串,但是由于某些原因,logfile和{}变量分配了一个元组。我在调试过程中注意到了这一点:

enter image description hereenter image description here

感谢你的反馈

谢谢


Tags: 文件脚本logjsonredshifthome参数ubuntu
1条回答
网友
1楼 · 发布于 2024-10-03 09:17:25

错误是由此处的多余逗号引起的:

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

移除它们,您将得到str形式的变量:

^{pr2}$

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

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

相关问题 更多 >