mashumaro icon indicating copy to clipboard operation
mashumaro copied to clipboard

Different results between standard library json and orjson

Open unratito opened this issue 1 month ago • 3 comments

  • mashumaro version: 3.13
  • Python version: 3.12.3
  • Operating System: Windows 11

Description

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())

And it prints these results:

{"inner": {"x": 5, "y": "hi"}}
{"inner": {"x": 5, "y": "hi"}}

While this equivalent code uses orjson:

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}}

unratito avatar May 29 '24 22:05 unratito