Making use of boto3 “out-of-the-box” DynamoDB Serializers
When working with DynamoDB, I’m pretty sure you already faced the problem of needing to create some kind of parser between dynamoDB object and python dictionary, since they are kind of different, mostly when working with big nested objects or even multiple different schemas.
What you did not know (and me neither, at least until a few days before writing this post) is that Amazon already has these tools ready-made for us to use, but it is not documented anywhere (except for the source code itself)!
They are called TypeSerializer and TypeDeserializer, and are packaged along boto3 (just under our noses). They are very easy to use, making our work a lot simpler:
from boto3.dynamodb.types import TypeDeserializer, TypeSerializerdef dynamo_obj_to_python_obj(dynamo_obj: dict) -> dict:
deserializer = TypeDeserializer()
return {
k: deserializer.deserialize(v)
for k, v in dynamo_obj.items()
}
def python_obj_to_dynamo_obj(python_obj: dict) -> dict:
serializer = TypeSerializer()
return {
k: serializer.serialize(v)
for k, v in python_obj.items()
}
The script used in this example can be found here.
Feel free to access my other repositories, I post a lot of snippets and personal projects that could help you!
Thanks for reading :)