What is the most efficient way of serializing a numpy array using simplejson?
I'd use simplejson.dumps(somearray.tolist())
as the most convenient approach (if I was still using simplejson
at all, which implies being stuck with Python 2.5 or earlier; 2.6 and later have a standard library module json
which works the same way, so of course I'd use that if the Python release in use supported it;-).
In a quest for greater efficiency, you could subclass json.JSONEncoder (in json
; I don't know if the older simplejson
already offered such customization possibilities) and, in the default
method, special-case instances of numpy.array
by turning them into list or tuples "just in time". I kind of doubt you'd gain enough by such an approach, in terms of performance, to justify the effort, though.
This shows how to convert from a numpy array to json and back to an array:
try:
import json
except ImportError:
import simplejson as json
import numpy as np
def arr2json(arr):
return json.dumps(arr.tolist())
def json2arr(astr,dtype):
return np.fromiter(json.loads(astr),dtype)
arr=np.arange(10)
astr=arr2json(arr)
print(repr(astr))
# '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
dt=np.int32
arr=json2arr(astr,dt)
print(repr(arr))
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])