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

19 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-18 16:48 +0100

1""" 

2Replacement for pydal's json serializer. 

3""" 

4 

5import datetime as dt 

6import json 

7from json import JSONEncoder 

8from typing import Any 

9 

10 

11class 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 

38def 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)