Last active
September 10, 2023 00:45
-
-
Save GabLeRoux/d6b2c2f7a69ebcd8430ea59c9bcc62c0 to your computer and use it in GitHub Desktop.
.env file to json using simple python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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))) |
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))
sweet, thanks!
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
to get it working with '=' inside value: