You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When using mixins to serialize data classes to JSON, standard library json and orjson give different results.
What I Did
This code uses standard library json:
from dataclasses import dataclass
from mashumaro.mixins.json import DataClassJSONMixin
import json
@dataclass
class A(DataClassJSONMixin):
x: int
@dataclass
class B(A):
y: str
@dataclass
class W(DataClassJSONMixin):
inner: A
b = B(5, 'hi')
w = W(b)
print(json.dumps(w.to_dict()))
print(w.to_json())
from dataclasses import dataclass
from mashumaro.mixins.orjson import DataClassORJSONMixin
import orjson
@dataclass
class A(DataClassORJSONMixin):
x: int
@dataclass
class B(A):
y: str
@dataclass
class W(DataClassORJSONMixin):
inner: A
b = B(5, 'hi')
w = W(b)
print(orjson.dumps(w.to_dict()))
print(w.to_json())
And it prints these other results:
b'{"inner":{"x":5,"y":"hi"}}'
{"inner":{"x":5}}
The text was updated successfully, but these errors were encountered:
I over-optimized the serialization of dataclasses using orjson to such an extent that it led to unpleasant consequences that I overlooked 😅. In short, when we build the serialization code for W, we build the code for turning dataclass A into a dictionary with types supported by orjson, since A is specified for inner. At runtime for B, this method will be called from the parent class A without the specific field y. I need to think more about what to do, since I don’t yet see any simple solutions other than getting rid of this optimization, which I wouldn’t want to do.
Description
When using mixins to serialize data classes to JSON, standard library
json
andorjson
give different results.What I Did
This code uses standard library
json
:And it prints these results:
While this equivalent code uses
orjson
:And it prints these other results:
The text was updated successfully, but these errors were encountered: