1+ import json
2+ from types import SimpleNamespace
3+ from osbot_utils .testing .__ import __
4+ from collections .abc import Mapping
5+ from osbot_utils .type_safe .primitives .domains .identifiers .safe_str .Safe_Str__Python__Identifier import Safe_Str__Python__Identifier
6+
7+ def dict_to_obj (target ):
8+ if isinstance (target , Mapping ):
9+ new_dict = {}
10+ for key , value in target .items (): # Sanitize the key to ensure it's a valid Python identifier
11+ safe_key = str (Safe_Str__Python__Identifier (str (key )))
12+ new_dict [safe_key ] = dict_to_obj (value ) # Recursively convert elements in the dict
13+ return __ (** new_dict )
14+ elif isinstance (target , list ): # Recursively convert elements in the list
15+ return [dict_to_obj (item ) for item in target ]
16+ elif isinstance (target , tuple ): # Recursively convert elements in the tuple
17+ return tuple (dict_to_obj (item ) for item in target )
18+
19+ return target
20+
21+ def obj_to_dict (target ): # Recursively converts an object (SimpleNamespace) back into a dictionary."""
22+ if isinstance (target , SimpleNamespace ): # Convert SimpleNamespace attributes to a dictionary
23+ return {key : obj_to_dict (value ) for key , value in target .__dict__ .items ()}
24+ elif isinstance (target , list ): # Handle lists: convert each item in the list
25+ return [obj_to_dict (item ) for item in target ]
26+ elif isinstance (target , tuple ): # Handle tuples: convert each item and return as a tuple
27+ return tuple (obj_to_dict (item ) for item in target )
28+ elif isinstance (target , set ): # Handle sets: convert each item and return as a set
29+ return {obj_to_dict (item ) for item in target }
30+ return target # Return non-object types as is
31+
32+ def str_to_obj (target ):
33+ if hasattr (target , 'json' ):
34+ return dict_to_obj (target .json ())
35+ return dict_to_obj (json .loads (target ))
36+
37+
38+ json_to_obj = str_to_obj
39+ obj = dict_to_obj
0 commit comments