When working with data processing or writing APIs, do you always find JSON serialization/deserialization frustratingly slow? Especially with large datasets, the standard json library is downright sluggish! Today, I’m sharing a hidden gem Python library—orjson—built with Rust, it’s 3 to 10 times faster than the standard library, and its usage is almost identical to json, making it perfect for beginners to pick up right away~

Step 1: Install orjson in 5 SecondsInstallation is super simple—open your terminal/command line and run just one line:
pip install orjson
No complicated dependencies—wait a few seconds for installation to finish, and you’re ready to go!
⚡ Core Usage: Even Simpler Than the Standard json Libraryorjson’s API is nearly identical to Python’s built-in json library—no new syntax to memorize, just replace the import statement~
1. Serialization: Convert Python Objects to JSON
The standard json library uses json.dumps(), while orjson uses orjson.dumps()—blazingly fast!
import orjson # Just replace the import statement
# Prepare a regular dictionary of data
data = {
"name": "Zhang San",
"age": 25,
"skills": ["Python", "Data Analysis", "Machine Learning"],
"is_student": False
}
# Serialize: Convert to JSON format (returns bytes, more memory-efficient than strings)
json_bytes = orjson.dumps(data)
print("Serialization result:", json_bytes)
# Decode to string if needed
json_str = json_bytes.decode("utf-8")
print("String format:", json_str)
The result is JSON output instantly—multiple times faster than the standard library, with even bigger gaps on large datasets!
2. Deserialization: Convert JSON to Python Objects
Corresponding to serialization, use orjson.loads()—supports both bytes and string formats, with equally fast parsing~
import orjson
# Prepare JSON data (bytes or str both work)
json_data = b'{"name": "Li Si", "scores": [95, 87, 92], "hobby": ["Reading", "Running"]}'
# Deserialize: Convert to Python dictionary
parsed_data = orjson.loads(json_data)
print("Name:", parsed_data["name"])
print("Average score:", f"{sum(parsed_data['scores']) / len(parsed_data['scores']):.1f}")
print("Hobbies:", parsed_data["hobby"])
Get a usable dictionary directly with no extra processing—beginners won’t hit snags!
A Dream for Beginners: Supports Special Data Types (No Custom Functions Needed)The standard json library doesn’t support types like datetime or UUID—serialization throws errors! But orjson natively supports these, so you can use them directly~
import orjson
from datetime import datetime, date
from uuid import uuid4 # Module to generate unique IDs
# Data containing special types
data = {
"id": uuid4(), # Unique ID
"created_at": datetime.now(), # Current time
"birthday": date(1995, 5, 15), # Date
"metadata": {"version": 1.0, "active": True}
}
# Serialize directly—no errors!
json_output = orjson.dumps(data)
print("JSON with special types:", json_output.decode("utf-8"))
No need to write complex custom serializers—save tons of code, and beginners no longer struggle with type conversions!
Practical Tips: Customize JSON Output (Beginner-Friendly)orjson offers flexible options (e.g., remove whitespace, sort keys) to meet different use cases~
import orjson
data = {
"message": "Performance Test",
"items": list(range(100)), # List from 0 to 99
"author": "Beginner"
}
# 1. Compact mode: Remove extra whitespace for concise JSON (saves memory)
compact_json = orjson.dumps(data, option=orjson.OPT_COMPACT)
print("Compact mode result:", compact_json.decode("utf-8"))
# 2. Sort keys: Output JSON fields in alphabetical order (easier to compare)
sorted_json = orjson.dumps(data, option=orjson.OPT_SORT_KEYS)
print("Key-sorted result:", sorted_json.decode("utf-8"))
# 3. Preserve newlines: Better readability (great for debugging)
pretty_json = orjson.dumps(data, option=orjson.OPT_APPEND_NEWLINE)
print("Newline-preserved result:", pretty_json.decode("utf-8"))
Just add an option parameter to achieve different effects—no complex syntax to memorize!
Visual Comparison: How Fast Is orjson Really?Talking the talk isn’t enough—let’s test the speed difference between orjson and the standard json library with code~
import orjson
import json
import time
# Generate 1000 user records (simulate large dataset scenario)
data = {"users": [{"id": i, "name": f"user_{i}", "age": 20+i%10} for i in range(1000)]}
# Test standard json library speed
start_time = time.time()
for _ in range(1000): # Serialize 1000 times
json.dumps(data)
json_time = time.time() - start_time
# Test orjson speed
start_time = time.time()
for _ in range(1000):
orjson.dumps(data)
orjson_time = time.time() - start_time
# Output results
print(f"Standard json library: {json_time:.3f} seconds")
print(f"orjson: {orjson_time:.3f} seconds")
print(f"orjson is {json_time/orjson_time:.1f}x faster than the standard library!")
Results typically show orjson is 3-10x faster—and the gap grows with larger datasets! For example, processing 100,000 records might take seconds with the standard library, but only hundreds of milliseconds with orjson.
Even Beginners Can Do This: Boost API Speed with orjsonIf you write APIs with Flask/Django, replacing json with orjson doubles response speed with minimal code changes~
from flask import Flask, Response
import orjson
app = Flask(__name__)
# API: Return user list
@app.route('/api/users')
def get_users():
users = [
{"id": 1, "name": "Zhang San", "email": "zhang@example.com"},
{"id": 2, "name": "Li Si", "email": "li@example.com"},
{"id": 3, "name": "Wang Wu", "email": "wang@example.com"}
]
# Serialize with orjson and return directly
json_data = orjson.dumps(users)
return Response(json_data, mimetype='application/json')
if __name__ == '__main__':
app.run(debug=True)
Start the Flask server and access the API—response speed is much faster than using json.dumps(), delivering a better user experience!
Must-Know for Beginners: orjson’s Advantages & Tips
Core Advantages (Why Choose It?)
- Blazing Fast: 3-10x faster than the standard
jsonlibrary—essential for large datasets and high-concurrency scenarios - Simple to Use: API matches the standard library—zero learning curve for beginners
- Special Type Support: Serialize
datetime/UUIDdirectly with no extra code - Memory Efficient: Returns bytes by default (more memory-efficient than strings)
Key Tips (Pitfalls to Avoid)
orjson returns bytes—decode with decode("utf-8") if you need a string•
Requires Python 3.8+—upgrade Python if your version is too old
No complex configuration needed—import and use directly (beginners don’t need to worry about setup errors)