Created
September 19, 2025 13:57
-
-
Save dbuschman7/43218690b5bc128fe40ada04b88ae5e9 to your computer and use it in GitHub Desktop.
JsonTreeContextManager
This file contains hidden or 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
| from typing import Any, Dict, List, Optional | |
| import json as pyjson | |
| from context.app_context import AppContext | |
| def convertToArray(path: str, delimiter: str = ".") -> List[str]: | |
| """Take a string and split it into parts based on given delimiter. Default delimiter is dot for path navigation.""" | |
| return path.split(delimiter) | |
| class JsonTreeContextManager: | |
| """ | |
| Context manager for assembling a nested dictionary tree, merging input at a given path, and outputting JSON. | |
| Uses AppContext for logging, config, and metrics. | |
| """ | |
| def __init__(self, app_context: AppContext, compact: bool = False): | |
| self.app_context = app_context | |
| self.compact = compact | |
| self.tree: Dict[str, Any] = {} | |
| def __enter__(self): | |
| self.app_context.info("JsonTreeContextManager: Entering context.") | |
| return self | |
| def __exit__(self, exc_type, exc_val, exc_tb): | |
| if exc_type: | |
| self.app_context.error(f"Exception in JsonTreeContextManager: {exc_val}") | |
| self.app_context.info("JsonTreeContextManager: Exiting context.") | |
| def merge_at_path(self, path: str, value: dict): | |
| """ | |
| Merge the given value (dict) into the tree at the location specified by the dot-separated path. | |
| """ | |
| self.app_context.debug(f"Merging at path '{path}': {value}") | |
| parts = convertToArray(path, ".") | |
| node = self.tree | |
| for i, part in enumerate(parts): | |
| if i == len(parts) - 1: | |
| # Merge at the leaf | |
| if part not in node or not isinstance(node[part], dict): | |
| node[part] = {} | |
| # Deep merge | |
| node[part] = self._deep_merge(node[part], value) | |
| else: | |
| if part not in node or not isinstance(node[part], dict): | |
| node[part] = {} | |
| node = node[part] | |
| def _deep_merge(self, d1: dict, d2: dict) -> dict: | |
| """Recursively merge d2 into d1.""" | |
| for k, v in d2.items(): | |
| if k in d1 and isinstance(d1[k], dict) and isinstance(v, dict): | |
| d1[k] = self._deep_merge(d1[k], v) | |
| else: | |
| d1[k] = v | |
| return d1 | |
| def to_json(self) -> str: | |
| """Return the assembled tree as a JSON string (formatted or compact).""" | |
| if self.compact: | |
| return pyjson.dumps(self.tree, separators=(",", ":"), ensure_ascii=False) | |
| else: | |
| return pyjson.dumps(self.tree, indent=2, ensure_ascii=False) |
This file contains hidden or 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
| # Pretty JSON | |
| pretty = JsonTreeContextManager(ctx, compact=False) | |
| with pretty: | |
| pretty.merge_at_path("root", {"val": 1}) | |
| json_str = pretty.to_json() | |
| assert "{\n" in json_str |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment