Reputation: 13
I am getting this error message when testing my lambda function.
{
"errorMessage": "the JSON object must be str, bytes or bytearray, not list",
"errorType": "TypeError",
"stackTrace": [
" File \"/var/task/handler.py\", line 90, in send_friend_request\n payload = json.loads(event['body'])\n",
" File \"/var/lang/lib/python3.7/json/__init__.py\", line 341, in loads\n raise TypeError(f'the JSON object must be str, bytes or bytearray, '\n"
]
}
The line it's complaining about is:
payload = json.loads(event['body'])
This is the function:
def accept_friend_request(event, context):
payload = json.loads(event['body'])
request_id = payload['request_id']
fromUsername = payload['fromUsername']
toUsername = payload['toUsername']
The format in which I'm sending in my son is:
{
"body": [
{
"fromUsername": "testUsrname",
"toUsername": "testsToUsername"
}
]
}
I have tried other formats to send the son like:
{
"fromUsername": "testUsrname",
"toUsername": "testsToUsername"
}
but that also throws an error:
{
"errorMessage": "'body'",
"errorType": "KeyError",
"stackTrace": [
" File \"/var/task/handler.py\", line 90, in send_friend_request\n payload = json.loads(event['body'])\n"
]
}
I am really lost here as to what to do. Am I sending the son in the wrong format or am I accepting it wrong with the json.loads?
Upvotes: 1
Views: 1687
Reputation: 9484
json.loads()
receives string as a parameter and converts it to python object (list/dictionary).
The problem in your code that event["body"]
is already python object (list, according to the error you shared). As mentioned in AWS Lambda docs for python event handler functions:
event – AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type
So you don't need to use json.loads()
to parse it into a python object. You can do:
# For the following event:
{
"body": [
{
"fromUsername": "testUsrname",
"toUsername": "testsToUsername"
}
]
}
def accept_friend_request(event, context):
request_id = context.aws_request_id
payload = event['body']
fromUsername = payload[0]['fromUsername']
toUsername = payload[0]['toUsername']
Upvotes: 1