Coverage for src/dataknobs_fsm/utils/json_encoder.py: 40%

1"""Custom JSON encoder for FSM objects."""

2

3 import json

4 from typing import Any

5

6

7 class FSMJSONEncoder(json.JSONEncoder):

8 """JSON encoder that handles FSM-specific types."""

9

10 def default(self, obj: Any) -> Any:

11 """Convert FSM objects to JSON-serializable forms.

12

13 Args:

14 obj: Object to serialize

15

16 Returns:

17 JSON-serializable representation

18 """

19 # Check for our custom serialization methods

20 if hasattr(obj, '__json__'):

21 return obj.__json__()

22 if hasattr(obj, 'to_dict'):

23 return obj.to_dict()

24

25 # Handle FSMData specifically

26 from dataknobs_fsm.core.data_wrapper import FSMData

27 if isinstance(obj, FSMData):

28 return obj.to_dict()

29

30 # Handle ExecutionResult specifically

31 from dataknobs_fsm.functions.base import ExecutionResult

32 if isinstance(obj, ExecutionResult):

33 return obj.to_dict()

34

35 # Fall back to default encoder

36 return super().default(obj)

37

38

39 def dumps(obj: Any, **kwargs) -> str:

40 """Serialize obj to JSON string with FSM support.

41

42 Args:

43 obj: Object to serialize

44 **kwargs: Additional arguments for json.dumps

45

46 Returns:

47 JSON string

48 """

49 kwargs.setdefault('cls', FSMJSONEncoder)

50 return json.dumps(obj, **kwargs)

51

52

53 def loads(s: str, **kwargs) -> Any:

54 """Deserialize JSON string to Python object.

55

56 Args:

57 s: JSON string

58 **kwargs: Additional arguments for json.loads

59

60 Returns:

61 Python object

62 """

63 return json.loads(s, **kwargs)