What is the most efficient way of serializing a numpy array using simplejson?
相关问题
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- streaming md5sum of contents of a large remote tar
- How to maintain order of key-value in DataFrame sa
- How to get the background from multiple images by
This shows how to convert from a 1D NumPy array to JSON and back to an array:
Building on tlausch's answer, here is a way to JSON-encode a NumPy array while preserving shape and dtype of any NumPy array -- including those with complex dtype.
One fast, though not truly optimal way is using Pandas:
I'd use
simplejson.dumps(somearray.tolist())
as the most convenient approach (if I was still usingsimplejson
at all, which implies being stuck with Python 2.5 or earlier; 2.6 and later have a standard library modulejson
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 oldersimplejson
already offered such customization possibilities) and, in thedefault
method, special-case instances ofnumpy.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.You can also answer this with just a function passed into
json.dumps
in this way:With
validated:
In order to keep dtype and dimension try this:
I just discovered tlausch's answer to this Question and realized it gives the almost correct answer for my problem, but at least for me it does not work in Python 3.5, because of several errors: 1 - infinite recursion 2 - the data was saved as None
since i can not directly comment on the original answer yet, here is my version: