Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created February 22, 2022 17:04
Show Gist options
  • Save nikoheikkila/7c32831c3d65adbcc4bee5b9930564c0 to your computer and use it in GitHub Desktop.
Save nikoheikkila/7c32831c3d65adbcc4bee5b9930564c0 to your computer and use it in GitHub Desktop.
A quick way to serialize Numpy Array to JSON
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