quantlab.utils.jsonable.to_jsonable#

quantlab.utils.jsonable.to_jsonable(value)[source]#

Return value rebuilt from JSON-safe types only.

Conversion rules:

  • dict becomes a dict with str keys and converted values; two keys that are equal after str() raise ValueError.

  • list, tuple, np.ndarray (any rank), pd.Series and pd.Index become lists, element by element; a 0-d array becomes its scalar; set and frozenset become lists in a deterministic order.

  • Booleans and integers (Python or numpy) become bool and int; floats become float with NaN and infinities mapped to None.

  • Timestamps, datetime64, datetime and date become ISO-8601 strings; timedeltas become str; NaT of either kind becomes None; Path and Decimal become str; an Enum is replaced by its converted value; str, int and None pass through.

Parameters:
valueobject

The object to convert.

Returns:
object

A structure made only of dict, list, str, int, float, bool and None.

Raises:
ValueError

If two dict keys collide after str() coercion.

TypeError

If value (or any nested value) has an unsupported type.

Examples

>>> to_jsonable({"sharpe": np.float64("nan"), "start": pd.Timestamp("2024")})
{'sharpe': None, 'start': '2024-01-01T00:00:00'}