Skip to content

Instantly share code, notes, and snippets.

@oduvan
Last active October 10, 2019 12:49
Show Gist options
  • Save oduvan/f31aaa4c59ece51842b4fcee13fb4264 to your computer and use it in GitHub Desktop.
Save oduvan/f31aaa4c59ece51842b4fcee13fb4264 to your computer and use it in GitHub Desktop.
json for np.ndarray, range and Iterator
import numpy as np
import json
from collections.abc import Iterator, Sequence
class CiOJSEncoderEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, np.generic):
return obj.item()
if isinstance(obj, Sequence) or isinstance(obj, Iterator):
return list(obj)
return json.JSONEncoder.default(self, obj)
a = np.array([[1, 2, 3], [4, 5, 6]])
json_dump = json.dumps({
'a': a, 'aa': [2, (2, 3, 4), a],
'bb': [2],
'cc': range(5),
'dd': map(lambda a: a**2, range(3))
}, cls=CiOJSEncoderEncoder)
print(json_dump)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment