Fatal1ty / mashumaro

Fast and well tested serialization library
Apache License 2.0
751 stars 44 forks source link

Supports `numpy.ndarray` type for `orjson` #207

Closed function2-llx closed 4 months ago

function2-llx commented 4 months ago

Is your feature request related to a problem? Please describe. The orjson library natively supports the numpy.ndarray type. Since numpy is a widely used library for numeric data, it will be great if this library can support it as well.

Fatal1ty commented 4 months ago

Orjson requires specifying numpy.ndarray option to support numpy data. You can do that in orjson_options. When enabled you need to use pass_through strategy for numpy data fields / types. Is it what you’re looking for?

function2-llx commented 4 months ago

Thank you for the suggestion! I achieve what I want with the code following:

from dataclasses import dataclass, field

from mashumaro import pass_through
from mashumaro.config import BaseConfig
from mashumaro.mixins.orjson import DataClassORJSONMixin
import numpy as np
from orjson import orjson

@dataclass
class A(DataClassORJSONMixin):
    x: np.ndarray = field(metadata={'serialize': pass_through, 'deserialize': np.array})

    class Config(BaseConfig):
        orjson_options = orjson.OPT_SERIALIZE_NUMPY

def main():
    a = A(np.array([1, 2, 3]))
    json_str = a.to_json()
    a_deserialized = A.from_json(json_str)
    assert np.array_equiv(a.x, a_deserialized.x)

if __name__ == '__main__':
    main()