Created
February 22, 2022 17:04
-
-
Save nikoheikkila/7c32831c3d65adbcc4bee5b9930564c0 to your computer and use it in GitHub Desktop.
A quick way to serialize Numpy Array to JSON
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 json import JSONEncoder, dumps | |
from typing import Any | |
import numpy as np | |
class NumpyEncoder(JSONEncoder): | |
def default(self, obj: object) -> Any: | |
if isinstance(obj, np.integer): | |
return int(obj) | |
if isinstance(obj, np.floating): | |
return float(obj) | |
if isinstance(obj, np.ndarray): | |
return obj.tolist() | |
return super(NumpyEncoder, self).default(obj) | |
def serialize(data: np.ndarray) -> str: | |
return dumps(data, cls=NumpyEncoder) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment