Created
January 2, 2021 15:13
-
-
Save keyro90/7e4d8619298e9652567f19826a37f6ca to your computer and use it in GitHub Desktop.
Convert JSON to environment variables for C# application settings
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
import argparse | |
import json | |
import re | |
import sys | |
from json.decoder import JSONDecodeError | |
MIN_ARGS = 2 | |
ERROR_MIN_ARGS = 1 | |
ERROR_FILE_FORMAT = 2 | |
def is_valid_env_name(v): | |
if not v: | |
return False | |
return re.match(r"^[a-zA-Z0-9_]+$", v) | |
def json2cs_env(obj, acc): | |
if isinstance(obj, dict): | |
for k in obj.keys(): | |
if not is_valid_env_name(k): | |
raise ValueError(f"{k} cannot be converted into env variable") | |
json2cs_env(obj[k], (acc + "__" + k if acc else k).upper()) | |
elif isinstance(obj, list): | |
if len(obj) > 0: | |
for index, _ in enumerate(obj): | |
json2cs_env(obj[index], acc + "__" + str(index)) | |
else: | |
first_part = f"{acc}=" | |
if obj is None: | |
print(first_part) | |
elif isinstance(obj, int): | |
print(f"{first_part}{obj}") | |
else: | |
print(f'{first_part}"{obj}"') | |
def init(): | |
args_s = sys.argv | |
if len(args_s) < MIN_ARGS: | |
print("Need 2 arguments.") | |
exit(ERROR_MIN_ARGS) | |
_, i_file = sys.argv | |
acc = '' | |
f = None | |
try: | |
f = open(i_file) | |
f_json = json.loads(f.read()) | |
json2cs_env(f_json, acc) | |
except IOError: | |
print("Input file accessible") | |
exit(ERROR_FILE_FORMAT) | |
except JSONDecodeError: | |
print("Invalid json format on input file") | |
finally: | |
f.close() | |
exit(0) | |
# Example usage: json2csenv.py filename.json | |
if __name__ == '__main__': | |
init() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment