env2json.py (1045B)
1 import os 2 import re 3 import sys 4 import json 5 6 DEFAULT_ENV_FILE = ".env.local" 7 env_vars = [] 8 9 if len(sys.argv) > 1: 10 ENV_FILE = sys.argv[1] 11 else: 12 ENV_FILE = DEFAULT_ENV_FILE 13 14 try: 15 with open(ENV_FILE, 'r', encoding='utf-8') as f: 16 content = f.read() 17 except FileNotFoundError: 18 print(f"エラー: ファイル '{ENV_FILE}' が見つかりません。") 19 print("使用方法: python convert.py [envファイルのパス]") 20 sys.exit(1) 21 22 for line in content.splitlines(): 23 line = line.strip() 24 if not line or line.startswith('#'): 25 continue 26 27 match = re.match(r'^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$', line) 28 if match: 29 key = match.group(1) 30 value = match.group(2).strip() 31 32 if value.startswith(('"', "'")) and value.endswith((value[0])): 33 value = value[1:-1] 34 35 env_vars.append({ 36 "key": key, 37 "value": value 38 }) 39 40 print(json.dumps(env_vars, indent=2, ensure_ascii=False))