I am writing a Lambda Python function on AWS. It retrieves a DynamoDB item and I want to return that back to the caller in a JSON format. If I don't serialise the item, there are errors with Python's json.dump function.
from boto3.dynamodb.types import TypeDeserializer, TypeSerializer
def serialize(dynamo_obj: dict) -> dict:
serializer = TypeSerializer()
return {
k: serializer.serialize(v)
for k, v in dynamo_obj.items()
}
table = dynamodb.Table(os.getenv('STORAGE_NAME'))
response = table.get_item(Key={'id': some_id})
item = response.get('Item', None)
if item:
return {
'statusCode': 200,
'headers': { 'Content-Type': 'application/json' },
'body': json.dumps(serialize(item))
}
However, when I serialise this way, the returned item contains some strange extra keys (some 'N' and 'S' keys that they don't appear in the dynamodb table).
What's the right way to make the dynamodb item compatible with JSON format so it can be returned back to the caller?