【问题标题】:JSON Post body not parsing as expectedJSON Post 正文未按预期解析
【发布时间】:2021-01-13 03:23:20
【问题描述】:

我有一个托管在 aws 上的 python 函数,它接受一个事件,然后做一堆事情,但本质上问题在于解析传入的 POST 请求。

我的代码如下所示:

import json

def lambda_handler(event, context):
    # TODO implement
    merchantid = json.dumps(event['body'])
    return {
        'statusCode': 200,
        'body': json.dumps(merchantid)
    }

为了发送 post 请求,我只是使用网站附带的 aws API Gateway 测试,所以它不应该是任何奇怪的编码。

当我传入一个 JSON 对象时,我希望 Mercerid 字段存储一个 json 对象。

相反,它返回这个字符串:

"\"{\\n    \\\"merchantEmail\\\": \\\"timcook@gmail.com\\\",\\n    \\\"customerEmail\\\": \\\"billgates@gmail.com\\\",\\n    \\\"merchantWallet\\\": \\\"mWallet\\\",\\n    \\\"transactionTotal\\\": 1.00,\\n    \\\"transactionDenomination\\\": \\\"AUD\\\",\\n    \\\"customerCurrency\\\": \\\"EUR\\\",\\n    \\\"merchantAccess\\\" : {\\n        \\\"merchantKey\\\": \\\"key\\\",\\n        \\\"merchantSecret\\\": \\\"secret\\\"\\n    },\\n    \\\"customerAccess\\\" : {\\n        \\\"customerKey\\\": \\\"ckey\\\",\\n        \\\"customerSecret\\\": \\\"csecret\\\"\\n    }\\n}\""

我从未见过这样的字符串,而且我似乎无法让它返回 JSON 格式。

有人知道我如何将其返回到正文中提交的原始 JSON 格式吗?

我应该提到,lambda_handler 使用测试事件与 JSON 完美配合,只有在我开始尝试使用 API Gateway 触发它时,我才开始遇到这个问题。

编辑: 这是我作为 PUT 请求的主体传递的 JSON 对象:

{
    "merchantEmail": "timcook@gmail.com",
    "customerEmail": "billgates@gmail.com",
    "merchantWallet": "mWallet",
    "transactionTotal": 1.00,
    "transactionDenomination": "AUD",
    "customerCurrency": "EUR",
    "merchantAccess" : {
        "merchantKey": "key",
        "merchantSecret": "secret"
    },
    "customerAccess" : {
        "customerKey": "ckey",
        "customerSecret": "csecret"
    }
}

编辑: 在我附加 API 网关之前,我正在处理它

merchantid = event['merchantEmail']

但是一旦我将它作为 PUT 的主体传入,将返回 502 内部服务器错误

【问题讨论】:

  • 为什么需要 json.dumps ?
  • 能否请您发布您放入的 JSON 对象,以便我们可以尝试重复您所做的事情?

标签: python json rest aws-lambda aws-api-gateway


【解决方案1】:

您进入 Lambda 函数的 event 参数是 python dict

假设您知道 dict 结构 - 您需要做的就是读取您要查找的值。

例子:

data = event['my_key']

【讨论】:

  • 我认为这是问题的一部分,如果我尝试像这样访问它merchantid = event['body'] print(type(merchantid)) 它会打印 而不是
【解决方案2】:

首先检查事件参数的数据类型是什么,是字符串还是字典。

如果body键值的数据类型是JSON (dict)

merchantid = event.get('body').get('merchantEmail')

如果正文键值的数据类型是String (str)

merchantid = json.loads(event.get('body')).get('merchantEmail')

【讨论】:

  • 感谢 Mrinal,使用负载对我有用,因为它被捕获为字符串。我有点困惑为什么它没有被捕获为字典,即使我在标题"Content-Type": "application/json" 中指定。你知道为什么会这样吗?
  • 对不起 Mrinal,如果我这样做 resp = json.loads(event.get('body')) print(resp) print(type(resp)),那么它会打印为 dict 类型。感谢您的帮助
  • 嵌套 JSON 以字符串形式出现,即使您将“Content-Type”设置为 application/json
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 2013-01-24
相关资源
最近更新 更多