CBOR (Concise Binary Object Representation)

1.0.0 · active · verified Sun Apr 12

The `cbor` library provides a Python implementation of RFC 7049, the Concise Binary Object Representation (CBOR). It allows encoding and decoding Python objects into a compact, binary format, offering an API similar to Python's built-in `json` module. The current version is 1.0.0, released in March 2024, indicating a stable and mature API, with a relatively slow release cadence focused on stability.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates encoding and decoding basic Python data types, including `datetime` objects and `bytes`, to and from CBOR binary format. It also shows how to use `dump` and `load` for streaming data to/from file-like objects.

import cbor
import io
import datetime

# Example Python dictionary with various types
data_to_encode = {
    'name': 'Alice',
    'age': 30,
    'is_student': False,
    'grades': [95.5, 88, 92.0],
    'address': None,
    'bio_bytes': b'\x01\x02\x03',
    'timestamp': datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0)
}

# 1. Encode to bytes
encoded_bytes = cbor.dumps(data_to_encode)
print(f"Encoded CBOR bytes: {encoded_bytes.hex()}")

# 2. Decode from bytes
decoded_data = cbor.loads(encoded_bytes)
print(f"Decoded data: {decoded_data}")
print(f"Decoded timestamp type: {type(decoded_data['timestamp'])}")

# 3. Encode/Decode using file-like objects (streaming)
buffer = io.BytesIO()
cbor.dump(data_to_encode, buffer)
buffer.seek(0)
stream_decoded_data = cbor.load(buffer)
print(f"Stream decoded data: {stream_decoded_data}")

view raw JSON →