Skip to content

Instantly share code, notes, and snippets.

@Jojozzc
Last active March 26, 2019 13:36
Show Gist options
  • Save Jojozzc/953dcd315001421fa9196b17dcd06712 to your computer and use it in GitHub Desktop.
Save Jojozzc/953dcd315001421fa9196b17dcd06712 to your computer and use it in GitHub Desktop.
convert ndarray to json
import json
class NumpyEncoder(json.JSONEncoder):
""" Special json encoder for numpy 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,)): #### This is the fix
return obj.tolist()
return json.JSONEncoder.default(self, obj)
path = './test.json'
npdata = np.zeros(3)
dumped = json.dumps(npdata, cls=NumpyEncoder)
with open(path, 'w') as f:
json.dump(dumped, f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment