How to pass a list as an environment variable?

The rationale

I recommend using JSON if you want to have data structured in an environment variable. JSON is simple to write / read, can be written in a single line, parsers exist, developers know it.

The solution

To test, execute this in your shell:

$ export ENV_LIST_EXAMPLE='["Foo", "bar"]'

Python code to execute in the same shell:

import os
import json

env_list = json.loads(os.environ['ENV_LIST_EXAMPLE'])
print(env_list)
print(type(env_list))

gives

['Foo', 'bar']
<class 'list'>

Package

Chances are high that you are interested in cfg_load

Debugging

If you see

JSONDecodeError: Expecting value: line 1 column 2 (char 1)

You might have used single-quotes instead of double-quotes. While some JSON libraries accept that, the JSON standard clearly states that you need to use double-quotes:

Wrong: "['foo', 'bar']"
Right: '["foo", "bar"]'

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)