stouputils.typing module#

This module provides utilities for typing enhancements such as JSON type aliases: - JsonDict - JsonList - JsonMap - JsonMutMap - IterAny

JsonDict#

A type alias for JSON dictionaries

alias of dict[str, Any]

JsonList#

A type alias for JSON lists

alias of list[Any]

JsonMap#

A type alias for JSON mapping

alias of Mapping[str, Any]

JsonMutMap#

A type alias for mutable JSON mapping

alias of MutableMapping[str, Any]

convert_to_serializable(obj: Any) Any[source]#

Recursively convert objects to JSON-serializable forms.

Objects with a to_dict() or asdict() method are converted to their dictionary representation. Dictionaries and lists are recursively processed.

Can also be used to convert nested structures containing custom objects, such as defaultdict, dataclasses, or other user-defined types.

Parameters:

obj (Any) – The object to convert

Returns:

The JSON-serializable version of the object

Return type:

Any

Examples

>>> from typing import defaultdict
>>> my_dict = defaultdict(lambda: defaultdict(int))
>>> my_dict['a']['b'] += 6
>>> my_dict['c']['d'] = 4
>>> my_dict['a']
defaultdict(<class 'int'>, {'b': 6})
>>> my_dict['c']
defaultdict(<class 'int'>, {'d': 4})
>>> convert_to_serializable(my_dict)
{'a': {'b': 6}, 'c': {'d': 4}}
>>> from dataclasses import dataclass
>>> @dataclass
... class Point:
...     x: int
...     y: int
>>> convert_to_serializable(Point(3, 4))
{'x': 3, 'y': 4}