Python3中如何正确设置值为JSON对象的os.environ环境变量?
正确设置JSON格式的os.environ环境变量
一、Bash环境下的正确设置方式
你遇到的报错是因为bash对转义字符的处理导致传递给Python的JSON字符串格式错误,以下是两种可行的解决方法:
方式1:用单引号包裹整个JSON字符串(推荐)
bash中,单引号内部的内容会被原样保留,不会解析转义字符,直接执行以下命令:
export INDEX_SET='{"index_all":false,"index_group":true,"index_channel":true,"exclude_chats":[],"include_chats":[1522205730]}'
方式2:双引号包裹时双重转义(不推荐,易出错)
如果必须使用双引号包裹环境变量值,需要对JSON内部的双引号进行两次转义(一次用于bash解析,一次保留给JSON格式):
export INDEX_SET="{\\\"index_all\\\":false,\\\"index_group\\\":true,\\\"index_channel\\\":true,\\\"exclude_chats\\\":[],\\\"include_chats\\\":[1522205730]}"
二、修正Python代码中的笔误
你的代码里存在变量名错误,index_settings_str并未定义,应该使用index_set_str,修正后的代码:
import os import json index_set_str = os.environ["INDEX_SET"].strip() index_settings = json.loads(index_set_str)
三、验证环境变量是否正确设置
在bash中执行以下命令,检查输出的JSON字符串是否格式正确(双引号完整):
echo $INDEX_SET
输出应为:
{"index_all":false,"index_group":true,"index_channel":true,"exclude_chats":[],"include_chats":[1522205730]}
内容的提问来源于stack exchange,提问作者data
相关产品推荐
相关产品推荐

