Porting from orjson¶
If you’re currently using orjson and considering migrating to msgspec,
this guide covers the key API differences and shows how to translate common
patterns.
Why migrate?¶
Both orjson and msgspec are high-performance JSON libraries written in
compiled languages.
There are a few reasons you might prefer msgspec:
Typed decoding and validation.
orjson.loadsalways returns plain Python builtins (dict,list, …). Withmsgspecyou can decode directly into typed objects (Struct,dataclass,TypedDict, etc.) while validating the schema in a single pass. See Usage for details.Schema evolution.
msgspechas first-class support for evolving schemas over time without breaking existing clients. See Schema Evolution.Multiple protocols.
msgspecalso supports MessagePack, YAML, and TOML with a consistent API, making it easy to switch between formats.JSON Schema generation.
msgspeccan generate JSON Schema definitions from your types viamsgspec.json.schema(). Useful for OpenAPI documentation and API tooling.
Basic usage¶
For most users, migration is straightforward – swap function names and you’re done:
# Before (orjson)
import orjson
data = orjson.dumps({"hello": "world"})
obj = orjson.loads(data)
# After (msgspec)
import msgspec
data = msgspec.json.encode({"hello": "world"})
obj = msgspec.json.decode(data)
Both return bytes from encoding and accept bytes or str for
decoding.
Typed decoding¶
The main advantage of msgspec over orjson is typed decoding. Instead of
getting a plain dict back, you can decode directly into structured types:
import msgspec
class User(msgspec.Struct):
name: str
age: int
email: str | None = None
data = b'{"name": "Alice", "age": 30}'
user = msgspec.json.decode(data, type=User)
print(user.name) # "Alice"
print(user.age) # 30
print(user.email) # None
This validates the data while decoding – if a field is missing or has the
wrong type, a msgspec.ValidationError is raised with a clear error message.
Encoder and Decoder classes¶
If you’re making multiple calls, using the Encoder and Decoder classes
is more efficient:
# orjson has no stateful encoder/decoder
# msgspec
encoder = msgspec.json.Encoder()
decoder = msgspec.json.Decoder(User)
data = encoder.encode(user)
user = decoder.decode(data)
Option mapping¶
orjson uses bitwise OPT_* flags. msgspec uses keyword arguments on
Encoder / Decoder or the encode / decode functions.
Sorting keys¶
# orjson
orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)
# msgspec
msgspec.json.encode(obj, order="sorted")
# Or with an Encoder
encoder = msgspec.json.Encoder(order="sorted")
msgspec also supports order="deterministic" which provides a
consistent ordering without the cost of full alphabetical sorting.
Pretty-printing¶
# orjson
orjson.dumps(obj, option=orjson.OPT_INDENT_2)
# msgspec -- use format() on already-encoded JSON
raw = msgspec.json.encode(obj)
pretty = msgspec.json.format(raw, indent=2)
Unlike orjson’s single-pass approach, msgspec uses a two-step process:
encode first, then format. msgspec.json.format works on any JSON bytes/str,
not just msgspec-encoded data, and supports arbitrary indent levels.
Custom type serialization¶
# orjson
def default(obj):
if isinstance(obj, complex):
return {"real": obj.real, "imag": obj.imag}
raise TypeError
orjson.dumps(obj, default=default)
# msgspec
def enc_hook(obj):
if isinstance(obj, complex):
return {"real"