Oslo Serialization Library
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
- breaking Support for Python 2.7 has been dropped since version 3.0.0. The minimum supported Python version is now 3.10 (as of oslo.serialization 5.9.1). Older Python versions will not work.
- deprecated The `oslo_serialization.yamlutils` module is deprecated since the Ussuri series (version 3.1.1) and its support will be removed in a future release. PyYAML is now considered safe by default.
- gotcha The `oslo_serialization.jsonutils.to_primitive` function (used internally by `dumps`) now explicitly raises a `ValueError` when the input value cannot be converted to a primitive type. Previously, it might have silently skipped or handled it differently.
- gotcha Serialization of Python traceback objects (e.g., as part of remote exceptions) is inherently lossy. The reconstructed traceback on the receiving end may not be as rich or complete as the original due to missing local stack frame information.
Install
-
pip install oslo-serialization
Imports
- jsonutils
from oslo_serialization import jsonutils
Quickstart
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}")