Reputation: 61
Trying to complete a lab for setting up a mobile game. But the lambda function is throwing the following error:
expected string or buffer: TypeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 34, in lambda_handler json_data = json.loads(msg)
From what I understand it is expecting a string but the variable msg is a dictionary that also contains list. Can someone explain how I can get this working? Should it be a json.dump instead? New to python and coding so please forgive if I'm not framing the question in the correct way. Code is below. Thanks in advance
def lambda_handler(event, context):
global client
print(event)
# check the receiver's queue url
if client == None:
client = boto3.resource('sqs')
records = event['Records'][0]
sns_data = records['Sns']
msg = sns_data['Message']
print(msg)
json_data = json.loads(msg)
type_of_msg = json_data['type']
sender = json_data['sender']
receiver = json_data['receiver']
amount = json_data['amount']
# queue_name = get_queue_name_by_account_id(receiver)
queue_name = USER_POOL_ID + "_" + receiver
# enqueue the message
queue = client.get_queue_by_name(QueueName=queue_name)
msg = {
"type": type_of_msg,
"amount": amount
}
res = queue.send_message(MessageBody=json.dumps(msg))
print(res)
return json_data['receiver']
Upvotes: 0
Views: 1245
Reputation: 388
json.loads needs a string or buffer, not a json.
msg is already a json, do not need to do json.loads.
below is a working example.
import boto3
import json
def lambda_handler(event, context):
client = None
USER_POOL_ID = 'xxxxx'
print(event)
# check the receiver's queue url
if client == None:
client = boto3.resource('sqs')
records = event['Records'][0]
sns_data = records['Sns']
msg = sns_data['Message']
print(msg)
json_data = msg
type_of_msg = json_data['type']
sender = json_data['sender']
receiver = json_data['receiver']
amount = json_data['amount']
# queue_name = get_queue_name_by_account_id(receiver)
queue_name = USER_POOL_ID + "_" + receiver
#enqueue the message
queue = client.get_queue_by_name(QueueName=queue_name)
msg = {
"type": type_of_msg,
"amount": amount
}
res = queue.send_message(MessageBody=json.dumps(msg))
print(res)
return json_data['receiver']
With sample test event for lambda:
{
"Records": [
{"Sns": {"Message": {"type": "a","sender": "b","receiver": "c","amount": "d"}}}
]
}
Hope this helps!
Upvotes: 1