-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_numpy.py
50 lines (45 loc) · 1.56 KB
/
json_numpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import numpy
import json
class EncodeFromNumpy(json.JSONEncoder):
"""
- Serializes python/Numpy objects via customizing json encoder.
- **Usage**
- `json.dumps(python_dict, cls=EncodeFromNumpy)` to get json string.
- `json.dump(*args, cls=EncodeFromNumpy)` to create a file.json.
"""
def default(self, obj):
import numpy
if isinstance(obj, numpy.ndarray):
return {
"_kind_": "ndarray",
"_value_": obj.tolist()
}
if isinstance(obj, numpy.integer):
return int(obj)
elif isinstance(obj, numpy.floating):
return float(obj)
elif isinstance(obj, range):
value = list(obj)
return {
"_kind_": "range",
"_value_": [value[0], value[-1] + 1]
}
return super(EncodeFromNumpy, self).default(obj)
class DecodeToNumpy(json.JSONDecoder):
"""
- Deserializes JSON object to Python/Numpy's objects.
- **Usage**
- `json.loads(json_string,cls=DecodeToNumpy)` from string, use `json.load()` for file.
"""
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
if '_kind_' not in obj:
return obj
kind = obj['_kind_']
if kind == 'ndarray':
return numpy.array(obj['_value_'])
elif kind == 'range':
value = obj['_value_']
return range(value[0], value[-1])
return obj