CVGenerator/modules/utils.py

35 lines
1019 B
Python

from json import loads
from os import path
from pathlib import Path
from typing import Any, Union
def json_read(filepath: Union[str, Path]) -> Any:
with open(str(filepath), "r", encoding="utf-8") as file:
output = loads(file.read())
return output
def nested_read(key: str, *args: str, data: dict) -> Any:
this_key = data
for dict_key in args:
this_key = this_key[dict_key]
return this_key[key]
def data_read(key: str, *args: str, locale: str) -> Any:
locale_file = (
json_read(Path("data", f"{locale}.json"))
if path.exists(Path("data", f"{locale}.json"))
else {}
)
try:
output = nested_read(key, *args, data=locale_file)
except (KeyError, ValueError):
default_file = locale_file = json_read(Path("data", f"default.json"))
try:
output = nested_read(key, *args, data=locale_file)
except (KeyError, ValueError):
return f"KEY NOT FOUND IN BOTH {locale} AND default"
return output