UserM
UserM

Reputation: 320

AWS DynamoDB data to json format in Python/Boto3/Lamba

I have a DynamoDB table, which needs to be converted to json format and shared across API response using Python/Boto3/AWS-Lambda environment.

userMetrics[
{
  "userid": 1234567890,  ==> key
  "likemetrics": 0,
  "lasttimestamp": 1604553995
},
{
  "userid": 1234567891,  ==> key
  "likemetrics": 0,
  "lasttimestamp": 1604553998
}]

I am trying to copy the entire DynamoDB table to json format using the examples mentioned in Formatting DynamoDB data to normal JSON in AWS Lambda but face error on execution as

{
"errorMessage": "'dynamodb.Table' object has no attribute 'items'",
"errorType": "AttributeError",
"stackTrace":[
"  File \"/var/task/lambda_function.py\", line 75, in lambda_handler\n    'usermetrics': json.dumps(from_dynamodb_to_json(dydb_userTable))\n",
"  File \"/var/task/lambda_function.py\", line 7, in from_dynamodb_to_json\n    return {k: d.deserialize(value=v) for k, v in item.items()}\n"
]
}

My lambda code implementation:

import json
import boto3
from boto3.dynamodb.types import TypeDeserializer, TypeSerializer

def from_dynamodb_to_json(item):
    d = TypeDeserializer()
    return {k: d.deserialize(value=v) for k, v in item.items()}

dydb = boto3.resource('dynamodb')
dydb_userTable = dydb.Table('userMetrics')

def lambda_handler(event, context):
        return {
            'statusCode': 200,
            'usermetrics': json.dumps(from_dynamodb_to_json(dydb_userTable))
        }

Upvotes: 2

Views: 4036

Answers (1)

Noel Llevares
Noel Llevares

Reputation: 16087

The Table (dydb_userTable in your code) object does not have the items that you're looking for. You need to call a method on that table that will retrieve the items for you such as dydb_userTable.scan() or dydb_userTable.query().

Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#table

Upvotes: 3

Related Questions