0

I have a Python 3.8 AWS Lambda function that receives a form input from a web app. The data from the form inputs passes to the Lambda function and is in the event dictionary. The problem is that lambda doesn't recognize it as a table and converts it into a string. My JS and Python code is below.

    function addPart(partName) {
        var raw = JSON.stringify({'partName':partName});
        $.ajax({
            method: 'POST',
            url: "Insert URL Here", // I have a real (working) invoke URL here
            headers: {
                Authorization: authToken
            },
            body: raw,
            contentType: 'application/json',
            success: completeRequest,
            error: function ajaxError(jqXHR, textStatus, errorThrown) {
                console.error('Error requesting ride: ', textStatus, ', Details: ', errorThrown);
                console.error('Response: ', jqXHR.responseText);
                alert('An error occured when adding your part:\n' + jqXHR.responseText);
            }
        });
    }
import boto3
import json

dynamodb = boto3.resource('dynamodb')

UniqueUser = "test"
partName = "default"

def lambda_handler(event, context):
    UniqueUser = event['requestContext']['authorizer']['claims']['sub']
    partName = event['partName']
    # partName = event['body']['partName']  
    table = dynamodb.Table('Parts')
    response = table.put_item(
       Item={
            'UserID': UniqueUser,
            'PartName': partName
        }
    )
    print(event)
    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps(partName)
    }

This is the relevant part of the response to the print(event) line. The issue is that, dispite being formatted like a Python library, it is in quotes and acts as a string. Does anyone know how to fix this?

'body': '{"partName":"test"}'
Seth A
  • 51
  • 7

2 Answers2

0

In your lambda_handler you have

 'body': json.dumps(partName)

Since partName is probably {"partName":"test"}, the json.dumps function is going to serlialize your partName into str, resulting in '{"partName":"test"}'.

To avoid that, you can return the partName directly:

    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*'
        },
        'body': partName
    }

The alternative is to use JSON.parse in JS on the client side to de-serialize json string.

Marcin
  • 215,873
  • 14
  • 235
  • 294
0

I solved this using the commented suggestion of deceze and parsed it into a dictionary. This is the code I paresd it with:

dictString = event['body']
attributeDict = ast.literal_eval(dictString)
partName = attributeDict["partName"]
Seth A
  • 51
  • 7