chwellofficial/nt360Slides
0
1from typing import List2 3from models.json_path_guide import JsonPathGuide, DictGuide, ListGuide4 5 6def get_dict_paths_with_key(data: dict, key: str) -> List[JsonPathGuide]:7 result = []8 9 def _find_paths(obj, current_path: List[DictGuide | ListGuide]):10 if isinstance(obj, dict):11 if key in obj:12 result.append(JsonPathGuide(guides=current_path.copy()))13 for k, v in obj.items():14 new_path = current_path + [DictGuide(key=k)]15 _find_paths(v, new_path)16 elif isinstance(obj, list):17 for i, item in enumerate(obj):18 new_path = current_path + [ListGuide(index=i)]19 _find_paths(item, new_path)20 21 _find_paths(data, [])22 return result23 24 25def get_dict_at_path(data: dict, path: JsonPathGuide) -> dict:26 current = data27 for guide in path.guides:28 if isinstance(guide, DictGuide):29 current = current[guide.key]30 elif isinstance(guide, ListGuide):31 current = current[guide.index]32 return current33 34 35def set_dict_at_path(data: dict, path: JsonPathGuide, value: dict):36 current = data37 for guide in path.guides[:-1]:38 if isinstance(guide, DictGuide):39 current = current[guide.key]40 elif isinstance(guide, ListGuide):41 current = current[guide.index]42 43 if path.guides:44 final_guide = path.guides[-1]45 if isinstance(final_guide, DictGuide):46 current[final_guide.key] = value47 elif isinstance(final_guide, ListGuide):48 current[final_guide.index] = value49 50 51def deep_update(original: dict, updates: dict) -> dict:52 for key, value in updates.items():53 if key in original:54 if isinstance(original[key], dict) and isinstance(value, dict):55 deep_update(original[key], value)56 elif isinstance(original[key], list) and isinstance(value, list):57 if len(value) == 0:58 continue59 elif len(value) == 1 and isinstance(value[0], dict):60 if len(original[key]) > 0 and isinstance(original[key][0], dict):61 deep_update(original[key][0], value[0])62 else:63 original[key][0] = (64 value[0] if len(original[key]) > 0 else value[0]65 )66 else:67 min_length = min(len(original[key]), len(value))68 for i in range(min_length):69 if isinstance(original[key][i], dict) and isinstance(70 value[i], dict71 ):72 deep_update(original[key][i], value[i])73 else:74 original[key][i] = value[i]75 elif not isinstance(value, (dict, list)):76 original[key] = value77 else:78 if not isinstance(value, (dict, list)):79 original[key] = value80 return original81 82 83def has_more_than_n_keys(obj: dict[str, object], n: int) -> bool:84 i = 085 for _ in obj.keys():86 i += 187 if i > n:88 return True89 return False90 