python using orjson to work with json

orjson is a json library that is fast and getting popular. 

Here are example code to work with same data 


import orjson
from dataclasses import dataclass
from datetime import datetime

@dataclass
class User:
    id: int
    name: str
    created_at: datetime

user = User(id=1, name="Alice", created_at=datetime.now())

# --- SERIALIZATION (Python Object -> JSON bytes) ---
json_bytes = orjson.dumps(user)
print(json_bytes)
# Output: b'{"id":1,"name":"Alice","created_at":"2026-10-04T15:12:00+00:00"}'

# --- DESERIALIZATION (JSON bytes/str -> Python Dict) ---
data = orjson.loads(json_bytes)
print(data)
# Output: {'id': 1, 'name': 'Alice', 'created_at': '2026-10-04T15:12:00+00:00'}

print(data['id']) # output 1



Comments

Popular posts from this blog

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

llama cpp running it in google colab