Coverage for src/typedal/serializers/as_json.py: 100%

1"""

2 Replacement for pydal's json serializer.

3"""

4

5 import datetime as dt

6 import json

7 from json import JSONEncoder

8 from typing import Any

9

10

11 class SerializedJson(JSONEncoder):

12 """

13 Custom encoder class with slightly improved defaults.

14 """

15

16 def default(self, o: Any) -> Any:

17 """

18 If no logic exists for a type yet, it is processed by this method.

19

20 It supports sets (turned into list), __json__ methods and will just str() otherwise.

21 """

22 if isinstance(o, set):

23 return list(o)

24 elif isinstance(o, dt.date):

25 return str(o)

26 elif hasattr(o, "__json__"):

27 if callable(o.__json__):

28 return o.__json__()

29 else:

30 return o.__json__

31 elif hasattr(o, "__dict__"):

32 return o.__dict__

33 else:

34 # warnings.warn(f"Unkown type {type(o)}")

35 return str(o)

36

37

38 def encode(something: Any, indent: int = None, **kw: Any) -> str:

39 """

40 Encode anything to JSON with some improved defaults.

41 """

42 return json.dumps(something, indent=indent, cls=SerializedJson, **kw)