BSON Codec for Python

0.5.10 · active · verified Sun Apr 12

The `bson` library provides an independent codec for the BSON (Binary JSON) serialization format, without depending on MongoDB. It offers functions to efficiently serialize Python data structures into BSON bytes and deserialize BSON data back into Python objects. The current version is 0.5.10. Based on recent GitHub activity and a history of addressing issues, it appears to be actively maintained, though releases are not on a fixed schedule.

Warnings

Install

Imports

Quickstart

This example demonstrates how to encode a Python dictionary containing common BSON types (string, datetime, ObjectId, float, list) into BSON bytes using `bson.dumps()`, and then decode it back into a Python dictionary using `bson.loads()`. It also shows how to catch `bson.errors.InvalidBSON` for corrupted or invalid BSON data.

import bson
from bson.objectid import ObjectId
from datetime import datetime, timezone

# Create a Python dictionary with BSON-compatible types
data = {
    "message": "Hello BSON!",
    "timestamp": datetime.now(timezone.utc), # Use timezone-aware datetime for best practice
    "_id": ObjectId(),
    "value": 123.45,
    "tags": ["python", "bson", "example"]
}

# Encode the dictionary to BSON bytes
bson_data = bson.dumps(data)
print(f"Encoded BSON (bytes): {bson_data}")

# Decode the BSON bytes back to a Python dictionary
decoded_data = bson.loads(bson_data)
print(f"Decoded data: {decoded_data}")
print(f"Type of decoded_data: {type(decoded_data)}")
print(f"Type of _id in decoded_data: {type(decoded_data['_id'])}")

# Demonstrate handling InvalidBSON
try:
    bson.loads(b"invalid_bson_data")
except bson.errors.InvalidBSON as e:
    print(f"Caught expected error: {e}")

view raw JSON →