Maximize JSON Performance with orjson for Python

Introduction to orjson

orjson is a fast, correct JSON library for Python. It benchmarks as the fastest Python library for JSON serialization and deserialization, making it an excellent choice for high-performance applications.

Installing orjson

pip install orjson

Using orjson for Serialization

Serialization (converting Python objects to JSON) with orjson is straightforward:


import orjson

data = {
    'name': 'John Doe',
    'age': 30,
    'city': 'New York'
}

json_data = orjson.dumps(data)
print(json_data)

Using orjson for Deserialization

Deserialization (converting JSON to Python objects) is just as simple:


json_data = b'{"name":"John Doe","age":30,"city":"New York"}'

data = orjson.loads(json_data)
print(data)

orjson API Examples

Custom Serialization

You can use default hooks for custom types:


import orjson

def default(obj):
    if isinstance(obj, MyCustomClass):
        return {'custom_key': obj.custom_value}
    raise TypeError

data = MyCustomClass()
json_data = orjson.dumps(data, default=default)
print(json_data)

Options for Controlling Serialization

orjson provides options to control serialization:


import orjson

data = {"key": "value"}

# Indent for pretty printing
json_data = orjson.dumps(data, option=orjson.OPT_INDENT_2)
print(json_data)

# Serializing without utf-8 validation
json_data = orjson.dumps(data, option=orjson.OPT_OMIT_MICROSECOND)
print(json_data)

Building an App with orjson

Here’s a simple example of using orjson in a FastAPI application:


from fastapi import FastAPI
import orjson

app = FastAPI()

class ORJSONResponse(JSONResponse):
    media_type = "application/json"

    def render(self, content: Any) -> bytes:
        return orjson.dumps(content)

@app.get("/items/{item_id}", response_class=ORJSONResponse)
async def read_item(item_id: int):
    return {"item_id": item_id, "value": "Some value"}

By using orjson with FastAPI, you can ensure that your JSON serialization is optimized for performance.

Hash: 006422b7771d7d760b493357c8325cb9d065a63684d20d9d0138b4351714076d

Leave a Reply

Your email address will not be published. Required fields are marked *