Skip to content

Instantly share code, notes, and snippets.

@abdullahainun
Last active July 10, 2026 12:24
Show Gist options
  • Select an option

  • Save abdullahainun/c1c71202b6f2fbf0ff88b7898cb9a3f5 to your computer and use it in GitHub Desktop.

Select an option

Save abdullahainun/c1c71202b6f2fbf0ff88b7898cb9a3f5 to your computer and use it in GitHub Desktop.
Convert dotenv to json
#!/usr/bin/env python3
import json
import sys
import argparse
def parse_env(filepath):
data = {}
with open(filepath) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k = k.strip()
v = v.strip().strip("'\"")
data[k] = v
return data
def main():
parser = argparse.ArgumentParser(description="Convert .env file to JSON")
parser.add_argument("input", help="Path to .env file")
parser.add_argument("-o", "--output", help="Output JSON file (default: stdout)")
parser.add_argument("--no-pretty", action="store_true", help="Compact JSON output")
args = parser.parse_args()
data = parse_env(args.input)
indent = None if args.no_pretty else 2
json_str = json.dumps(data, indent=indent, ensure_ascii=False)
if args.output:
with open(args.output, "w") as f:
f.write(json_str)
f.write("\n")
else:
print(json_str)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment