Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
.env file to json using simple python
#!/usr/bin/env python
import json
import sys
try:
dotenv = sys.argv[1]
except IndexError as e:
dotenv = '.env'
with open(dotenv, 'r') as f:
content = f.readlines()
# removes whitespace chars like '\n' at the end of each line
content = [x.strip().split('=') for x in content if '=' in x]
print(json.dumps(dict(content)))
@GabLeRoux
Copy link
Author

GabLeRoux commented Jan 13, 2017

.env:

SOME_ENV_VAR_DEBUG=True
SOME_EMPTY_VALUE=''

Usage combined with jq

python env-to-json.py | jq

output

{
  "SOME_ENV_VAR_DEBUG": "True",
  "SOME_EMPTY_VALUE": "''"
}

Script could be improved with more validity checks or maybe loading env variables somehow instead of splitting on =. Could add usage help, etc. But it does what I needed 🥇

If you'd like to have "" instead of "''", you may edit the python script, but I personally used sed:

 | sed "s#\"''\"#\"\"#"

@paradite
Copy link

paradite commented Apr 22, 2019

to get it working with '=' inside value:

- content = [x.strip().split('=') for x in content if '=' in x]
+ content = [x.strip().split('=', 1) for x in content if '=' in x]

@jackbow
Copy link

jackbow commented Nov 18, 2021

With comment support and substitution (eg. A=$B —> "A": "B_Value"):

#!/usr/bin/env python
import json
import sys
import re

try:
    dotenv = sys.argv[1]
except IndexError as e:
    dotenv = '.env'

with open(dotenv, 'r') as f:
    content = f.readlines()

contentList = [x.strip().split('#')[0].split('=', 1) for x in content if '=' in x.split('#')[0]]
contentDict = dict(contentList)
for k, v in contentList:
    for i, x in enumerate(v.split('$')[1:]):
        key = re.findall(r'\w+', x)[0]
        v = v.replace('$' + key, contentDict[key])
    contentDict[k] = v

print(json.dumps(contentDict))

@GabLeRoux
Copy link
Author

GabLeRoux commented Nov 18, 2021

sweet, thanks!

@9bany
Copy link

9bany commented Aug 23, 2022

Delete white space start/end string with trip():

- contentDict[k] = v
+ contentDict[k] = v.strip()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment