Python 3 将 json 值读取为元组

标签 python json python-3.x

我已经为我的 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 中,因为一个变量被分配了正确的数据类型作为字符串,但由于某种原因变量 logfileconnectionfile 它正在分配一个元组。我在调试中发现了这一点:

enter image description here enter image description here

感谢您的反馈

谢谢

最佳答案

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

            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'>
>>>

关于Python 3 将 json 值读取为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50537522/

相关文章:

Python:防止 python 索引数组。列表索引必须是整数

javascript - 附加 JSON 对象编号 - 故障排除

javascript - 无法从动态 json 获取数据

json - Angular 7 HTTP GET 发送 JSON 对象作为参数

python - 如何从动态表中检索数据 - selenium python

python - 我的代码的哪一部分导致了 "Time-Out Error",为什么?

python - 有人对 telnetlib.expect() 有好感吗?

python - "PACKAGES DO NOT MATCH THE HASHES" pip 错误

python - 如何在 Python - GEKKO 中构建和打印循环生成的优化值列表?

python - 有没有一种(简单的)方法可以在 Python 中解析 CRL?