Created
February 5, 2018 13:13
-
-
Save erwindassen/af736dd4a56fb256b6875c0147a4fa9a to your computer and use it in GitHub Desktop.
# This snippet shows how to serialize one or more numpy arrays into a form fit for HTTP transport
# namely a JSON object
# Author: Erwin Dassen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This snippet shows how to serialize one or more numpy arrays into a form fit for HTTP transport | |
# namely a JSON object | |
# Author: Erwin Dassen | |
from io import BytesIO | |
import numpy as np | |
import json | |
A = np.array([[1.+1.j, 1.j], [-1.j, 1.-1.j]], dtype=np.complex64) # dtype not necessary for np.complex128 | |
# Serialize | |
fh_serial = BytesIO() | |
np.savez_compressed(fh_serial, A=A, B=A.T) # the second and subsequent parameter(s) indicate how to access the array by name upon deserialization | |
hex_serial = fh_serial.getbuffer().hex() # str type | |
json_serial = json.dumps(hex_serial) | |
# Deserialize | |
hex_deserial = json.loads(json_serial) # str type | |
bytes_deserial = bytes.fromhex(hex_deserial) | |
fh_deserial = BytesIO(bytes_deserial) | |
X = np.load(fh_deserial) | |
# Test | |
assert np.all(X['A'] == A) | |
assert np.all(X['B'] == A.T) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment