dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

Add support for encoding numpy integer and floating point types

Open pvanheus opened this issue 2 years ago • 1 comments

Feel free to ignore if this is too much of an edge case for your module, but I found a need to serialise dataclasses to JSON that had NumPy types (int64 etc) in them. This PR adds support for encoding NumPy types, but only if the numpy module is available.

pvanheus avatar Apr 12 '22 19:04 pvanheus

It would be nice to handle numpy arrays as well. Something like:

elif np_available and _isinstance_safe(o, np.ndarray):
    result = o.tolist()

sebastian-ruiz avatar Aug 23 '22 14:08 sebastian-ruiz

It would be nice to handle numpy arrays as well. Something like:

elif np_available and _isinstance_safe(o, np.ndarray):
    result = o.tolist()

Thanks, I have belatedly incorporated your suggestion, simplified the code and added a test for encoding to JSON,

pvanheus avatar Jun 11 '23 10:06 pvanheus

I wonder why not use encoder/decoder instead? I've seen people do this with fields being pandas Dataframes

george-zubrienko avatar Jun 14 '23 06:06 george-zubrienko

Thanks for your PR. Imo, I believe dataclasses-json should only support native types out of the box while 3rd-party types like numpy can be de/encoded with custom encoders.

matt035343 avatar Jun 25 '23 12:06 matt035343

I'd say if the author added instead an example for docs with custom encoder/decoder for numpy, that would have helped many people. I'll wait a bit, if no reaction follows, I'll close this one and update docs with examples for both numpy and pandas.

george-zubrienko avatar Jul 01 '23 07:07 george-zubrienko

Closing this in favor of #470

matt035343 avatar Aug 12 '23 14:08 matt035343