Oslo Serialization Library

5.9.1 · active · verified Sat Apr 11

The oslo.serialization library, part of the OpenStack Oslo project, provides robust utilities for representing Python objects in transmittable and storable formats like JSON and MessagePack. It aims to offer high-quality, stable, and consistent serialization functionalities for OpenStack and other projects. The library is actively maintained and currently at version 5.9.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `oslo_serialization.jsonutils.dumps` and `loads` to serialize and deserialize a custom Python object. It highlights the automatic handling of types like `datetime` and `UUID` by `jsonutils.to_primitive`, which `dumps` utilizes by default.

from oslo_serialization import jsonutils
import datetime
import uuid

class CustomObject:
    def __init__(self, name, value, created_at=None):
        self.name = name
        self.value = value
        self.id = str(uuid.uuid4())
        self.created_at = created_at or datetime.datetime.now(datetime.timezone.utc)

    # oslo_serialization.jsonutils.to_primitive will handle this automatically
    # but for custom types, you might explicitly define how to convert them.
    # For datetime and UUID, jsonutils has built-in support.
    def to_dict(self):
        return {
            'name': self.name,
            'value': self.value,
            'id': self.id,
            'created_at': self.created_at.isoformat()
        }

# Example usage
obj = CustomObject('test_item', 123.45)

# Serialize to JSON string
json_string = jsonutils.dumps(obj, indent=2)
print(f"Serialized JSON:\n{json_string}")

# Deserialize from JSON string
data_dict = jsonutils.loads(json_string)
print(f"Deserialized dictionary: {data_dict}")

# Demonstrate to_primitive (used internally by dumps by default)
primitive_data = jsonutils.to_primitive(obj)
print(f"Primitive representation: {primitive_data}")

view raw JSON →