Skip to content

Instantly share code, notes, and snippets.

@thepushkarp
Last active July 6, 2022 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thepushkarp/f5ae8fa7d13bf6f730f917f5f172093b to your computer and use it in GitHub Desktop.
Save thepushkarp/f5ae8fa7d13bf6f730f917f5f172093b to your computer and use it in GitHub Desktop.
Store a numpy.ndarray or any nested-list composition as JSON
# Link: https://stackoverflow.com/a/47626762/10307491
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]},
cls=NumpyEncoder)
print(json_dump)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment