简体   繁体   中英

AWS Python Lambda Function JSON format

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?"
}]

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM