torch_ecg.utils.make_serializable#

torch_ecg.utils.make_serializable(x: Any, drop_unserializable: bool = True, drop_paths: bool = False) → list | dict | str | int | float | bool | None[source]#

Recursively convert object into JSON-serializable form.

Rules#

  • NDArray → list

  • np.generic → Python scalar

  • dict → new dict with only serializable values

  • list/tuple → list with only serializable values

  • str/int/float/bool/None → kept

  • if drop_unserializable:

    anything else (like Path, custom classes) → dropped (return None)

    else:

    fallback to str(x)

param x:

Input object to be converted.

type x:

Any

param drop_unserializable:

Whether to drop unserializable objects (return None), or convert them to string with str(x).

Added in version 0.0.32.

type drop_unserializable:

bool, default=True

param drop_paths:

If True, drop all filesystem paths (Path objects and strings that look like paths).

Added in version 0.0.32.

type drop_paths:

bool, default=False

returns:

A JSON-serializable object, or None if dropped.

rtype:

Optional[Union[list, dict, str, int, float, bool]]

Examples

>>> import numpy as np
>>> make_serializable(np.array([1, 2, 3]))
[1, 2, 3]
>>> make_serializable({"a": np.float64(3.14), "b": Path("file.txt")})
{'a': 3.14, 'b': 'file.txt'}
>>> make_serializable({"a": np.float64(3.14), "b": Path("file.txt")}, drop_paths=True)
{'a': 3.14}