Utility method to derive both keys and Python object types from specially formatted dictionary keys and make
their respective values into Python objects of those types.
Parameters: |
-
json_dict
(Dict[str, Any] )
–
JSON dictionary that may contain keys in the format type.key_name (e.g.
path.root_directory) with corresponding string values representing Python objects of that type.
|
Returns: |
-
Dict[str, Any]
–
dict[str, Any]: Dictionary with both keys and Python object values derived from specially formatted JSON
dictionary keys.
|
Source code in src/pyobjson/utils.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81 | def derive_typed_key_value_pairs(json_dict: Dict[str, Any]) -> Dict[str, Any]:
"""Utility method to derive both keys and Python object types from specially formatted dictionary keys and make
their respective values into Python objects of those types.
Args:
json_dict (Dict[str, Any]): JSON dictionary that may contain keys in the format type.key_name (e.g.
path.root_directory) with corresponding string values representing Python objects of that type.
Returns:
dict[str, Any]: Dictionary with both keys and Python object values derived from specially formatted JSON
dictionary keys.
"""
derived_key_value_pairs = {}
for key, value in json_dict.items():
if key.count(".") == 1:
type_str, key = key.split(".")
if type_str == "path": # handle posix paths
value = Path(value)
elif type_str == "callable": # TODO: handle proper serialization and reconstruction of functions
value = None
derived_key_value_pairs[key] = value
else:
# add key-value pair without modification if key is not formatted with a single "." to indicate a value type
derived_key_value_pairs[key] = value
return derived_key_value_pairs
|