Last active
July 10, 2026 12:24
-
-
Save abdullahainun/c1c71202b6f2fbf0ff88b7898cb9a3f5 to your computer and use it in GitHub Desktop.
Convert dotenv to json
This file contains hidden or 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 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