1

I need to serialize a numpy array to some JSON-compatible form. Since the framework I'm using doesn't give me access to the JSON encoder/decoder object, I'm stuck serializing a numpy array to something that can then be marshalled into JSON. I've opted for either array.tobytes or array.tostring (both seem to be essentially the same thing).

Below is an example which illustrates my problem:

import numpy as np

a = np.random.rand(1024, 1024)  # create array of random values
b = array.tobytes()  # serialize array
a2 = np.fromstring(b)

When I inspect the value of a2, I find that it only contains the first line of the original a. In other words, a2 == a[0, :].

How can I decode the full array?

Louis Thibault
  • 20,240
  • 25
  • 83
  • 152

1 Answers1

1

Actually numpy.fromstring() returns a single dimensional array of 1024X1024 intead of a 2 Dimensional array, All you need to do is reshape into 1024X1024,

Try this :-

import numpy as np
a = np.random.rand(1024, 1024)  # create array of random values
b = array.tobytes()
np.fromstring(b).reshape(1024,1024)
Namit Singal
  • 1,506
  • 12
  • 26
  • Thanks! Is there a way to preserve the shape information when serializing? I can't expect the un-serialization end to know anything about the array dimensions *a priori*. – Louis Thibault Jun 07 '15 at 20:04
  • Unfortunately there isn't, you could probably write a wrapper class around numpy for the same and use that class too probably at the un-serialization end, I don't really know of a cleaner way. – Namit Singal Jun 07 '15 at 20:13
  • Cleaner solution: http://stackoverflow.com/questions/30698004/how-can-i-serialize-a-numpy-array-e-g-to-string-while-preserving-matrix-dimen?lq=1 – daniel451 Jun 07 '15 at 20:52