import logging from pathlib import Path from traceback import format_exc from typing import Any, Union from ujson import JSONDecodeError, dumps, loads logger = logging.getLogger(__name__) def json_load(filepath: Union[str, Path]) -> Any: """Load json file ### Args: * filepath (`Union[str, Path]`): Path to input file ### Returns: * `Any`: Some json deserializable """ with open(filepath, "r", encoding="utf8") as file: try: output = loads(file.read()) except JSONDecodeError: logger.error( "Could not load json file %s: file seems to be incorrect!\n%s", filepath, format_exc(), ) raise except FileNotFoundError: logger.error( "Could not load json file %s: file does not seem to exist!\n%s", filepath, format_exc(), ) raise file.close() return output def json_write(contents: Union[list, dict], filepath: Union[str, Path]) -> None: """Save contents into json file ### Args: * contents (`Union[list, dict]`): Some json serializable * filepath (`Union[str, Path]`): Path to output file """ try: with open(filepath, "w", encoding="utf8") as file: file.write(dumps(contents, ensure_ascii=False, indent=4)) file.close() except Exception as exp: logger.error("Could not save json file %s: %s\n%s", filepath, exp, format_exc()) return def config_get(key: str, *args: str) -> Any: """Get value of the config key ### Args: * key (`str`): The last key of the keys path. * *args (`str`): Path to key like: dict[args][key]. ### Returns: * `Any`: Value of provided key """ this_dict = json_load(Path("config.json")) this_key = this_dict for dict_key in args: this_key = this_key[dict_key] return this_key[key]