在 AWS Lambda 中返回 JSON 数据作为字符串,可以使用以下代码示例:
import json
def lambda_handler(event, context):
# 构建要返回的数据
response_data = {
'message': 'Hello, world!',
'status': 'success'
}
# 将数据转换为 JSON 字符串
response_body = json.dumps(response_data)
# 返回 JSON 字符串
return {
'statusCode': 200,
'body': response_body,
'headers': {
'Content-Type': 'application/json'
}
}
这个示例使用 Python 编写 AWS Lambda 函数。在函数中,我们首先创建一个包含要返回的数据的字典 response_data。然后,使用 json.dumps() 方法将 response_data 转换为 JSON 字符串。最后,我们返回一个包含 JSON 字符串的响应,其中 statusCode 设置为 200,body 设置为 JSON 字符串,headers 设置为 Content-Type: application/json。