1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import json import numpy as np
class NumpyEncoder(json.JSONEncoder): """ Special json encoder for np types """ def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): return int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) elif isinstance(obj, (np.ndarray,)): return obj.tolist() return json.JSONEncoder.default(self, obj)
my_data = { "array": np.array([1, 2, 3]), "int64": np.int64(42) }
with open('my_filename.json', 'w') as f: json.dump(my_data, f, indent=4, cls=NumpyEncoder)
|