我创建了一个简单的python 3.7 lambda函数:
import json
import boto3
s3 = boto3.client("s3")
def lambda_handler(event, context):
bucket = "nubi-data"
key = "core/user.json"
try:
data = s3.get_object(Bucket=bucket, Key=key)
json_data = data['Body'].read()
#return json_data
return {
'statusCode': 200,
"headers": {"Content-Type": "application/json"},
'body': json.loads(json_data)
}
except Exception as e:
print(e)
raise e
此函数从s3存储桶中读取json文件。json文件如下所示:
{ "id": 1, "name": "John", "pwd": "password" }
当我在AWS控制台的function editor屏幕中进行测试时,函数成功运行,输出如下:
Response: { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": { "id": 1, "name": "John", "pwd": "password" } }
Request ID: "f57de02f-44dd-4854-9df9-9f3a8c90031d"
Function Logs: START RequestId: f57de02f-44dd-4854-9df9-9f3a8c90031d Version: $LATEST END RequestId: f57de02f-44dd-4854-9df9-9f3a8c90031d REPORT RequestId: f57de02f-44dd-4854-9df9-9f3a8c90031d Duration: 260.70 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 84 MB
Thu Mar 21 21:04:08 UTC 2019 : Endpoint response body before transformations: {"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": {"id": 1, "name": "John", "pwd": "password"}} Thu Mar 21 21:04:08 UTC 2019 : Execution failed due to configuration error: Malformed Lambda proxy response Thu Mar 21 21:04:08 UTC 2019 : Method completed with status: 502
改变
到
^{pr2}$API网关需要一个字符串作为输出,}从字符串中创建一个JSON。如果你知道NodeJS,它们相当于JSON.stringify以及JSON.parse分别是。在
json.dumps
正是这样做的。^另一方面,{示例
生产
同时
生产
此信息可在official docs中找到
编辑
还有一件事我和OP都没有注意到,
data['Body'].read()
不返回JSON本身,而是返回一个缓冲区。它需要先解码。在json_data = data['Body'].read().decode('utf-8')
将返回stringized JSON(当然,只是因为您的文件是JSON),所以在return语句中,您应该可以这样做:相关问题 更多 >
编程相关推荐