Created
July 25, 2015 03:00
-
-
Save nevsan/53bf9ca013514789088d to your computer and use it in GitHub Desktop.
JSON serialization support for NumPy ndarray objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import partial | |
import io | |
import json | |
import numpy as np | |
def as_numpy(dct): | |
"""JSON decoder for NumPy ndarrays.""" | |
if '__numpy__' in dct: | |
return np.load(io.BytesIO(dct['data'].encode('latin-1'))) | |
return dct | |
class NumpyEncoder(json.JSONEncoder): | |
"""JSON Encoder for NumPy ndarrays.""" | |
def default(self, obj): | |
if isinstance(obj, np.ndarray): | |
f = io.BytesIO() | |
np.save(f, obj) | |
f.seek(io.SEEK_SET) | |
data = f.read().decode('latin-1') | |
return {'__numpy__': True, 'data': data} | |
return super().default(obj) | |
json_dumps = partial(json.dumps, cls=NumpyEncoder) | |
json_dump = partial(json.dump, cls=NumpyEncoder) | |
json_loads = partial(json.loads, object_hook=as_numpy) | |
json_load = partial(json.load, object_hook=as_numpy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment