【问题标题】:JSON error expected string or buffer: TypeError lambda function failingJSON 错误预期字符串或缓冲区:TypeError lambda 函数失败
【发布时间】:2017-12-09 17:53:57
【问题描述】:

尝试完成设置手机游戏的实验室。但是 lambda 函数抛出以下错误:

预期的字符串或缓冲区:TypeError
回溯(最近一次通话最后一次):
文件“/var/task/lambda_function.py”,第 34 行,在 lambda_handler json_data = json.loads(msg)

据我了解,它需要一个字符串,但变量 msg 是一个还包含列表的字典。有人可以解释我怎样才能让它工作吗?它应该是一个 json.dump 吗? python和编码的新手,所以如果我没有以正确的方式提出问题,请原谅。代码如下。提前致谢

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']

【问题讨论】:

  • 请编辑上面的示例代码以获得正确的缩进。
  • 他刚才说那是一本字典。
  • 你应该使用json.dumps

标签: python json amazon-web-services lambda


【解决方案1】:

json.loads 需要一个字符串或缓冲区,而不是 json

msg已经是json了,不需要做json.loads

下面是一个工作示例。

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']

带有 lambda 的示例测试事件:

{
  "Records": [
      {"Sns": {"Message": {"type": "a","sender": "b","receiver": "c","amount": "d"}}}
  ]
}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-15
    • 2013-04-18
    • 2016-01-24
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多