从ApiGateway中的lambda Go返回Json

gjmwrych  于 2023-08-01  发布在  Go
关注(0)|答案(2)|浏览(121)

我试图使这一工作,我想要的是得到json作为输出从lambda时,从API网关调用一些嵌套的json。
这是我所期望的,{ "data": {"username":"Random User","Age":20}", "message": "This is sample" },但我得到转义json { "data": "\n\t{\n\t\t\"username\":\"Random User\",\n\t\t\"Age\":20\n\t}", "message": "This is sample" }
我正在尝试示例代码

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

type Response struct {
    StatusCode int               `json:"statusCode"`
    Headers    map[string]string `json:"headers"`
    Body       string            `json:"body"`
}

type RequestBody struct {
    Data    any    `json:"data"`
    Message string `json:"message"`
}

const (
    data string = `
    {
        "username":"Random User",
        "Age":20
    }`
)

func EventHandler(request events.APIGatewayProxyRequest) (Response, error) {
    response := Response{}
    log.Println(request.Headers)
    body := RequestBody{Data: data, Message: "This is sample"}
    b, _ := json.Marshal(body)
    response.Body = string(b)
    response.StatusCode = http.StatusOK
    log.Println("Before Return")
    return response, nil
}

func main() {
    lambda.Start(EventHandler)
}

字符串

hgncfbus

hgncfbus1#

这是因为要封送(编码为JSON)一个已经包含JSON对象的字符串。相反,试试这个:

var data = map[string]any {
        "username":"Random User",
        "Age":20
    }

字符串
或者你也可以这样做:

body := RequestBody{Data: json.RawMessage(data), Message: "This is sample"}

jbose2ul

jbose2ul2#

应用程序将data中的JSON编码为JSON。使用json.RawMessage消除额外的JSON编码级别。

var data = json.RawMessage(`
    {
        "username":"Random User",
        "Age":20
    }`)

字符串

相关问题