Coverage for src/dataknobs_fsm/utils/json_encoder.py: 40%
20 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-20 16:46 -0600
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-20 16:46 -0600
1"""Custom JSON encoder for FSM objects."""
3import json
4from typing import Any
7class FSMJSONEncoder(json.JSONEncoder):
8 """JSON encoder that handles FSM-specific types."""
10 def default(self, obj: Any) -> Any:
11 """Convert FSM objects to JSON-serializable forms.
13 Args:
14 obj: Object to serialize
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()
25 # Handle FSMData specifically
26 from dataknobs_fsm.core.data_wrapper import FSMData
27 if isinstance(obj, FSMData):
28 return obj.to_dict()
30 # Handle ExecutionResult specifically
31 from dataknobs_fsm.functions.base import ExecutionResult
32 if isinstance(obj, ExecutionResult):
33 return obj.to_dict()
35 # Fall back to default encoder
36 return super().default(obj)
39def dumps(obj: Any, **kwargs) -> str:
40 """Serialize obj to JSON string with FSM support.
42 Args:
43 obj: Object to serialize
44 **kwargs: Additional arguments for json.dumps
46 Returns:
47 JSON string
48 """
49 kwargs.setdefault('cls', FSMJSONEncoder)
50 return json.dumps(obj, **kwargs)
53def loads(s: str, **kwargs) -> Any:
54 """Deserialize JSON string to Python object.
56 Args:
57 s: JSON string
58 **kwargs: Additional arguments for json.loads
60 Returns:
61 Python object
62 """
63 return json.loads(s, **kwargs)