python - 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
了一个元组。我在调试中赶上了这一点:
感谢您的反馈
谢谢
解决方案
该错误是由那里的多余逗号引起的:
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 - 如果对熊猫数据框python进行其他操作
- node.js - 如何创建 .deb 包以便更新时不会覆盖特定文件?
- c - 为什么第二个差异与其他差异如此不同,在循环中使用 gettimeofday?
- asp.net-core - 是否可以使用“真实”证书来保护 Net Core Worker 服务(又名 Windows 服务)?
- authentication - Authserver.exe 将无法启动
- karate - 如何在空手道功能文件中配置 .pem 证书
- typescript - linter 错误静态方法 lodash typescript
- flutter - 在颤动中自定义滚动条指示器高度的任何方法
- firebase - Campaign_details 事件未记录在 Firebase 中
- asp.net - 视图中的分页问题,分页栏