askuzenkov
askuzenkov

Reputation: 89

Go Gin: how to marshall []byte to json without quotes

I try to return json from my test app. The result returns with quotes and escape characters. How to return raw json?

type Row struct {
    Id    int    `json:"id"`
    Value string `json:"value"`
    Name  string `json:"name"`
}

func GetTestData() map[string]string {
    res := map[string]string{}

//db query and other logic

     for resultQuery.Next() {
        singleRow := Row{}
        errorScan := resultQuery.Scan(
            &singleRow.Id,
            &singleRow.Value,
            &singleRow.Name,
        )

        //error scan here 

        res[singleRow.Name] = singleRow.Value
    }

    return res
}

And call this func

   g.GET("/test", func(c *gin.Context) {
        out, _ := json.Marshal(services.GetTestData())
        c.JSON(200, gin.H{"output": string(out)})
    })

Query result:

{
    "output": "{\"val one\":\"name one\",\"val two\":\"name two\"}"
}

I want to get result like

{
    "output": {"val one": "name one", "val two": "name two "}
}

I read about json.RawMessage but can't understand how to implemente it in this case. Thanks everyone!

Upvotes: 1

Views: 996

Answers (1)

Iprefer Water
Iprefer Water

Reputation: 71

I think it's what you are trying to do

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/test", func(c *gin.Context) {
        res := GetTestData()
        c.JSON(http.StatusOK, gin.H{
            "output": res,
        })
    })
    r.Run()
}

type Row struct {
    Id    int    `json:"id"`
    Value string `json:"value"`
    Name  string `json:"name"`
}

func GetTestData() map[string]string {
    res := map[string]string{}

    //db query and other logic

    row1 := Row{
        Id:    1,
        Value: "1",
        Name:  "row_1",
    }

    row2 := Row{
        Id:    2,
        Value: "2",
        Name:  "row_2",
    }

    //error scan here

    res[row1.Name] = row1.Value
    res[row2.Name] = row2.Value

    return res
}

this is what I have on localhost:8080/test

{
        "output": {
            "row_1": "1",
            "row_2": "2"
        }
    }

Upvotes: 1

Related Questions