Skip to content

Instantly share code, notes, and snippets.

@tsoe77
Created March 27, 2023 18:38
Show Gist options
  • Select an option

  • Save tsoe77/68d1519d90a73804d12fa83eed20bbe9 to your computer and use it in GitHub Desktop.

Select an option

Save tsoe77/68d1519d90a73804d12fa83eed20bbe9 to your computer and use it in GitHub Desktop.
a script to convert any dot env file to json and vice versa
import json
import sys
import os
def dotenv_to_json(dotenv_path, json_path):
with open(dotenv_path) as f:
data = f.readlines()
result = {}
for line in data:
if line.strip() and not line.startswith('#'):
key, value = line.strip().split('=', 1)
result[key] = value
with open(json_path, 'w') as f:
json.dump(result, f, indent=2)
def json_to_dotenv(json_path, dotenv_path):
with open(json_path) as f:
data = json.load(f)
with open(dotenv_path, 'w') as f:
for key, value in data.items():
f.write(f'{key}={value}\n')
if __name__ == '__main__':
if len(sys.argv) < 4:
print("Usage: python dotenv_to_json.py <convert_type> <input_file> <output_file>")
print("Convert Types: dotenv_to_json or json_to_dotenv")
sys.exit(1)
convert_type, input_file, output_file = sys.argv[1], sys.argv[2], sys.argv[3]
if convert_type == 'dotenv_to_json':
dotenv_to_json(input_file, output_file)
elif convert_type == 'json_to_dotenv':
json_to_dotenv(input_file, output_file)
else:
print("Invalid convert_type! Use 'dotenv_to_json' or 'json_to_dotenv'.")
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment