Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return Json From lambda Go in ApiGateway

Im trying to make this work, what i want is to get json as output from lambda when called from API gateway with some nested json.

This is what i expect,
{ "data": {"username":"Random User","Age":20}", "message": "This is sample" }
but im getting escaped json
{ "data": "\n\t{\n\t\t\"username\":\"Random User\",\n\t\t\"Age\":20\n\t}", "message": "This is sample" }

the sample code which im trying

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}

>Solution :

This is because to marshaled (encoded as JSON) a string that already contains a JSON object. Instead, try this:

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

Or you can also do:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading