GBMR
GBMR

Reputation: 604

Get String value from lambda DynamoDB

I have a lambda func that gets values from my DynamoDB table. The String values are printed to my cloud watch logs but look like this {'S': 'Random String here'} . How can I just get the string by itself. I understand that the S represents the attribute value for string https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html . Lambda Code:

import json
import boto3
from boto3.dynamodb.conditions import Key, Attr

def lambda_handler(event, context):
    e = event['Records'][0]
    message = e['dynamodb']['NewImage']['latestMessage']
    print(message) # This prints {'S': 'Random message here'}

How can I get the string without the {'S': ' '}

Upvotes: 0

Views: 495

Answers (1)

Sarthak Jain
Sarthak Jain

Reputation: 2096

You can use the Boto DynamoDB Serializer/Deserializer to convert between DynamoDB and Python Objects.

import json
import boto3
from boto3.dynamodb.conditions import Key, Attr
deserializer = boto3.dynamodb.types.TypeDeserializer()

def lambda_handler(event, context):
    e = event['Records'][0]
    message = e['dynamodb']['NewImage']
    deserialized = {k: deserializer.deserialize(v) for k,v in message.items()}
    print(deserialized) # This will print {'latestMessage': 'Random message here'}

Upvotes: 1

Related Questions