Coverage for src/accsr/conversions.py : 94%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from math import isinf, isnan
2from typing import Any, Dict, Union
4import numpy as np
7def to_json_compatible_value(value):
8 """
9 Cast a numerical value to be compatible with json serialization.
11 >>> import numpy
12 >>> from accsr.conversions import to_json_compatible_value
13 >>> to_json_compatible_value(numpy.array([1, 2, 3]))
14 [1, 2, 3]
15 >>> to_json_compatible_value(numpy.array([[1], [2], [3]]))
16 [[1], [2], [3]]
17 >>> to_json_compatible_value(numpy.nan)
18 'nan'
19 >>> to_json_compatible_value(3.3)
20 3.3
22 """
23 if isinstance(value, np.ndarray):
24 value = value.tolist()
25 elif isinstance(value, np.integer):
26 value = int(value)
27 elif isinstance(value, np.floating):
28 value = float(value)
29 elif not isinstance(value, float) and not isinstance(value, int):
30 value = str(value)
32 if isinstance(value, float) and (isinf(value) or isnan(value)):
33 value = str(value)
34 return value
37def to_json_compatible_dict(
38 d: Dict[Union[str, int], Any]
39) -> Dict[Union[str, int], Any]:
40 """
41 Calls the to_json_compatible_value function for each dict entry.
42 Does not support nested dicts.
44 >>> from accsr.conversions import to_json_compatible_dict
45 >>> import numpy
46 >>> to_json_compatible_dict({'a': numpy.int32(1), 'b': numpy.array([1, 2])})
47 {'a': 1, 'b': [1, 2]}
48 """
49 return {k: to_json_compatible_value(v) for k, v in d.items()}