|
1
|
|
|
from typing import Optional, Callable, Dict |
|
2
|
|
|
|
|
3
|
|
|
from jsons._dump_impl import dump |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
def default_dict_serializer( |
|
7
|
|
|
obj: dict, |
|
8
|
|
|
cls: Optional[type] = None, |
|
9
|
|
|
*, |
|
10
|
|
|
strict: bool = False, |
|
11
|
|
|
strip_nulls: bool = False, |
|
12
|
|
|
key_transformer: Optional[Callable[[str], str]] = None, |
|
13
|
|
|
types: Optional[Dict[str, type]] = None, |
|
14
|
|
|
**kwargs) -> dict: |
|
15
|
|
|
""" |
|
16
|
|
|
Serialize the given ``obj`` to a dict of serialized objects. |
|
17
|
|
|
:param obj: the dict that is to be serialized. |
|
18
|
|
|
:param cls: not used. |
|
19
|
|
|
:param strict: if ``True`` the serialization will raise upon any the |
|
20
|
|
|
failure of any attribute. Otherwise it continues with a warning. |
|
21
|
|
|
:param strict: a bool to determine if the serializer should be strict |
|
22
|
|
|
(i.e. only dumping stuff that is known to ``cls``). |
|
23
|
|
|
:param strip_nulls: if ``True`` the resulting dict will not contain null |
|
24
|
|
|
values. |
|
25
|
|
|
:param key_transformer: a function that will be applied to all keys in the |
|
26
|
|
|
resulting dict. |
|
27
|
|
|
:param types: a ``dict`` with attribute names (keys) and their types |
|
28
|
|
|
(values). |
|
29
|
|
|
:param kwargs: any keyword arguments that may be given to the serialization |
|
30
|
|
|
process. |
|
31
|
|
|
:return: a dict of which all elements are serialized. |
|
32
|
|
|
""" |
|
33
|
|
|
result = dict() |
|
34
|
|
|
types = types or dict() |
|
35
|
|
|
for key in obj: |
|
36
|
|
|
obj_ = obj[key] |
|
37
|
|
|
cls_ = types.get(key, None) |
|
38
|
|
|
dumped_elem = dump(obj_, |
|
39
|
|
|
cls=cls_, |
|
40
|
|
|
key_transformer=key_transformer, |
|
41
|
|
|
strip_nulls=strip_nulls, |
|
42
|
|
|
strict=strict, |
|
43
|
|
|
**kwargs) |
|
44
|
|
|
if not (strip_nulls and dumped_elem is None): |
|
45
|
|
|
if key_transformer: |
|
46
|
|
|
key = key_transformer(key) |
|
47
|
|
|
result[key] = dumped_elem |
|
48
|
|
|
return result |
|
49
|
|
|
|