0
votes

I am using the following Python function in AWs Lambda:

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

#always start with the lambda_handler
def lambda_handler(event, context):

    # make the connection to dynamodb
    dynamodb = boto3.resource('dynamodb')

    # select the table
    table = dynamodb.Table("test")

    response = table.query(
    KeyConditionExpression=Key('coursename').eq('intro')
    )
    data = response['Items']
    return {'body' : data}

It outputs the following JSON - notice the "body" key? This is creating some issues when I try to use the response in my app because I have to reference the "body" as part of the response.

JSON response from Lambda

{
    "body": [{
        "coursename": "introto1",
        "course-lesson-name": "Welcome to One! "
    }, {
        "coursename": "introto2",
        "course-lesson-name": "What is One?"
    }, {
        "coursename": "introto2",
        "course-lesson-name": "What Can We do with One?"
    }]
}

This is the JSON format I need my Python function to output. Can this be done in AWS Lambda?

JSON format I need:

[{
    "coursename": "introto1",
    "course-lesson-name": "Welcome to One! "
}, {
    "coursename": "introto2",
    "course-lesson-name": "What is One?"
}, {
    "coursename": "introto2",
    "course-lesson-name": "What Can We do with One?"
}]
1
What happens if you change return {'body' : data} to return data ? - Mark B
Dang - that easy, huh? I feel a little foolish, but thanks - it worked like a charm. - DataGuy

1 Answers

2
votes

The response is in that format because you are explicitly wrapping it in a JSON object with a body property. Change return {'body' : data} to return data.