Coverage for src / agent_contracts / utils / json.py: 50%

12 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-09 00:42 +0900

1"""JSON utilities. 

2 

3Provides datetime-aware JSON serialization. 

4""" 

5from __future__ import annotations 

6 

7import json 

8from datetime import datetime 

9from typing import Any 

10 

11 

12def json_serializer(obj: Any) -> str: 

13 """Serialize non-JSON objects like datetime. 

14  

15 Args: 

16 obj: Object to serialize 

17  

18 Returns: 

19 Serialized string 

20  

21 Raises: 

22 TypeError: If object cannot be serialized 

23 """ 

24 if isinstance(obj, datetime): 

25 return obj.isoformat() 

26 raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") 

27 

28 

29def json_dumps(obj: Any, **kwargs) -> str: 

30 """JSON dumps with datetime support. 

31  

32 Args: 

33 obj: Object to serialize to JSON 

34 **kwargs: Additional arguments for json.dumps 

35  

36 Returns: 

37 JSON string 

38 """ 

39 kwargs.setdefault("ensure_ascii", False) 

40 kwargs.setdefault("default", json_serializer) 

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