diff --git a/src/utils/json.py b/src/utils/json.py new file mode 100644 index 0000000..31682b5 --- /dev/null +++ b/src/utils/json.py @@ -0,0 +1,41 @@ +import json +from typing import Any, Dict, Optional + + +class JsonUtils: + @staticmethod + def pretty_print(data: Any) -> str: + return json.dumps(data, indent=2, ensure_ascii=False) + + @staticmethod + def minify(data: Any) -> str: + return json.dumps(data, separators=(",", ":")) + + @staticmethod + def merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]: + result = base.copy() + for key, value in override.items(): + if key in result and isinstance(result[key], dict) and isinstance(value, dict): + result[key] = JsonUtils.merge(result[key], value) + else: + result[key] = value + return result + + @staticmethod + def get_nested(data: Dict[str, Any], key_path: str, default: Any = None) -> Any: + keys = key_path.split(".") + current = data + for key in keys: + if isinstance(current, dict) and key in current: + current = current[key] + else: + return default + return current + + @staticmethod + def validate_json(json_str: str) -> tuple[bool, Optional[Any], Optional[str]]: + try: + data = json.loads(json_str) + return True, data, None + except json.JSONDecodeError as e: + return False, None, str(e)