Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python orjson: dumps, loads, and serialization options

Use Python's orjson library for fast JSON serialization. Learn orjson.dumps and orjson.loads options, dataclass support, datetime and UUID handling, and key differences from the standard json module.

~6 min readPython
#orjson#JSON serialization#Python performance#dataclasses
Illustration of Python orjson serializing a dictionary into compact JSON bytes with speed and efficiency.

When you need to serialize Python objects to JSON and parse JSON back into Python, the standard json module is often the default choice. For high-throughput services, orjson provides a faster alternative with a similar API. This article covers how to use orjson.dumps() and orjson.loads() effectively, which options matter, and where the library behaves differently from the standard library.

Why Choose orjson Over the Standard json Module

orjson is a Rust-backed JSON library that can be faster than json in many serialization and deserialization workloads. It also supports native serialization for common Python types like datetime, UUID, and dataclasses without requiring custom converters for every case. The API is intentionally close to json, so migrating is straightforward in most applications.

The main differences appear in the options on dumps() and in how orjson handles non-serializable types. For example, orjson.dumps() returns bytes by default, not a str. That matters when you write to a file, return a response, or send data over a network. orjson.loads() accepts str, bytes, or bytearray input, which is convenient.

Basic Usage: dumps and loads

Start with the simplest case: serialize a dictionary and parse it back.

python
import orjson data = {'name': 'Ada', 'roles': ['admin', 'developer']} serialized = orjson.dumps(data) print(serialized) # b'...compact JSON bytes...' parsed = orjson.loads(serialized) print(parsed) # {'name': 'Ada', 'roles': ['admin', 'developer']}

dumps() returns a bytes object. If you need a str, call .decode() on the result. The output is compact: no extra spaces after commas or colons. This is intentional and often desirable for storage and transmission.

loads() accepts bytes, str, or bytearray. It raises orjson.JSONDecodeError on invalid input, just as json.loads() raises a JSONDecodeError. The error details may differ, but the exception is still a ValueError subclass.

Controlling Output with OPT_* Flags

orjson.dumps() accepts an option parameter that combines flags from orjson.OPT_*. These flags change formatting or serialization behavior. Common flags include:

FlagEffect
OPT_INDENT_2Pretty-print with two spaces per indentation level
OPT_SORT_KEYSSort dictionary keys alphabetically
OPT_NAIVE_UTCTreat naive datetime objects as UTC
OPT_UTC_ZSerialize UTC datetimes with a Z suffix instead of +00:00
OPT_SERIALIZE_NUMPYSerialize NumPy arrays natively
OPT_SERIALIZE_DATACLASSSerialize dataclass instances without custom code
OPT_SERIALIZE_UUIDSerialize UUID objects as strings
OPT_OMIT_MICROSECONDSOmit microseconds from datetime and time objects

Combine flags with the bitwise OR operator |.

python
import orjson data = {'b': 1, 'a': 2} pretty_sorted = orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS) print(pretty_sorted.decode())

Output:

json
{ "a": 2, "b": 1 }

OPT_SORT_KEYS makes the output deterministic, which helps with caching and debugging. OPT_INDENT_2 is useful for logs or human-readable configuration files, but it increases payload size.

Serializing Dataclasses and Custom Objects

orjson can serialize dataclass instances natively if you pass OPT_SERIALIZE_DATACLASS. Without this flag, dumps() raises TypeError for dataclass objects.

python
import orjson from dataclasses import dataclass @dataclass class User: id: int name: str user = User(id=1, name='Ada') # Without the flag, this raises TypeError: # orjson.dumps(user) serialized = orjson.dumps(user, option=orjson.OPT_SERIALIZE_DATACLASS) print(serialized) # b'...'

The flag also handles nested dataclasses, lists of dataclasses, and dataclasses containing other supported types. For arbitrary objects, provide a default callable. dumps() invokes it for types it cannot handle natively and uses the returned value as the serializable representation.

python
import orjson from decimal import Decimal def default(obj): if isinstance(obj, Decimal): return str(obj) raise TypeError(f'Object of type {type(obj).__name__} is not serializable') value = Decimal('3.14') print(orjson.dumps({'pi': value}, default=default)) # b'...'

default is only called for types that orjson cannot handle natively. If you pass OPT_SERIALIZE_DATACLASS, dataclasses are handled before default is invoked.

Handling datetime and UUID Types

orjson has built-in support for datetime, date, time, and UUID objects, but flag choices affect the output format.

For datetime objects, orjson serializes them as RFC 3339 strings. Naive datetimes are serialized without a timezone offset. To treat naive datetimes as UTC, use OPT_NAIVE_UTC. To append Z instead of +00:00 for UTC datetimes, use OPT_UTC_Z.

python
import orjson from datetime import datetime, timezone utc = datetime(2025, 1, 1, 12, 0, tzinfo=timezone.utc) print(orjson.dumps(utc)) # b'...' print(orjson.dumps(utc, option=orjson.OPT_UTC_Z)) # b'...'

For UUID objects, use OPT_SERIALIZE_UUID to serialize them as strings. Without the flag, orjson raises TypeError.

python
import orjson from uuid import uuid4 uuid_obj = uuid4() print(orjson.dumps(uuid_obj, option=orjson.OPT_SERIALIZE_UUID))

These options control the output format without requiring custom converters. If you need a different format, use the default function or preprocess the data before calling dumps.

Performance and Memory Considerations

orjson is designed for speed, but its actual advantage depends on your data shape and workload. The library avoids Python-level loops for serialization and uses a Rust implementation that writes directly to a buffer. This reduces CPU usage and can lower memory overhead compared to json when the data set is large.

However, do not assume orjson is always faster. For very small payloads, the cost of calling into Rust may be comparable to json. The benefit becomes more visible with larger JSON documents or when serializing many objects in a tight loop.

One operational detail: orjson.dumps() returns a bytes object, which is immutable. If you need to modify the result, copy it first. Also, orjson does not support streaming serialization like json.JSONEncoder.iterencode(). For very large data structures, you may need to chunk your data manually or use another approach.

Memory usage is generally lower than json because orjson avoids creating intermediate Python objects for every nested value. Still, the output bytes object holds the entire serialized result in memory. For extremely large payloads, consider a streaming or file-based approach.

Error Handling and Edge Cases

orjson.dumps() raises TypeError for unsupported types, and orjson.loads() raises orjson.JSONDecodeError for malformed JSON. The error messages may differ from json, but you should still handle both exception types explicitly in production.

python
import orjson try: orjson.dumps({'key': object()}) except TypeError as e: print(f'Serialization failed: {e}') try: orjson.loads(b'{"invalid": true,') except orjson.JSONDecodeError as e: print(f'Parse failed: {e}')

orjson.JSONDecodeError is a subclass of ValueError, so catching ValueError also works. When using default, make sure it raises TypeError for truly unsupported objects; otherwise, you may get confusing downstream errors.

orjson also has a few edge cases worth knowing:

  • It serializes float('nan') and float('inf') as null by default. This differs from json, which writes NaN and Infinity. The latter are not valid JSON, so the orjson behavior is often the safer choice.
  • It does not support cyclic references. If your data contains a reference cycle, dumps() raises RecursionError or TypeError. The standard json module also fails on cycles, so you need to break cycles before serializing.

When to Use orjson in Production

orjson is a good fit for services that serialize JSON frequently, such as REST APIs, message queues, or caching layers. Its speed and native support for common types reduce boilerplate code. However, it is a third-party dependency, so you need to manage it in your deployment environment. The library is actively maintained and supports current Python versions, but verify compatibility with your Python runtime before relying on it.

For applications that depend on json.JSONEncoder subclassing or custom default logic, migrating to orjson requires adjusting to its flag-based options. The API is similar enough that most code can be changed by replacing json.dumps with orjson.dumps and handling the bytes return type.

If you work with NumPy arrays, orjson can serialize them efficiently with OPT_SERIALIZE_NUMPY. This is an advantage over json, where you would need to convert arrays to lists manually. It makes orjson particularly useful in data pipelines and scientific computing contexts.

One final consideration: orjson is a compiled Rust extension. Prebuilt wheels exist for most mainstream Linux, macOS, and Windows environments, but check your deployment target if you use an uncommon platform or Python version.

Using orjson with Web Frameworks

Some frameworks let you swap in a JSON response class that uses orjson at the framework boundary. FastAPI, for example, provides an ORJSONResponse class. If orjson is installed, you can make it the default response class:

python
from fastapi import FastAPI from fastapi.responses import ORJSONResponse app = FastAPI(default_response_class=ORJSONResponse) @app.get('/data') def get_data(): return {'message': 'hello'}

The exact configuration depends on the framework and version. The general principle is to configure the response class once, rather than wrapping every return value manually. If a library expects str output, decode the bytes returned by orjson.dumps() before passing it along.

Final Implementation Notes

When integrating orjson, start by replacing the most performance-critical json calls. Measure the impact in your actual workload instead of assuming it will be faster. Keep the bytes versus str distinction in mind, and handle TypeError and JSONDecodeError explicitly.

For dataclasses, pass OPT_SERIALIZE_DATACLASS. For datetime and UUID, choose the appropriate flags. If you need compatibility with existing JSON consumers, test the output format carefully, especially timezone offsets and non-finite floats.

orjson is a robust tool for Python JSON serialization, but it is not a drop-in replacement for every use case. Its performance benefits and native type support make it a strong choice for modern Python services, provided you understand its options and limitations.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.