Go Gin 将 json 响应转换为 base64

Go Gin converting json response to base64

我正在尝试将数据库查询数据作为 json 响应发送。这是我的控制器:

import (
    "fmt"
    "github.com/json-iterator/go"
    "log"
)

func GetNewsPapers()  []byte{
    db := GetDB()

    var json = jsoniter.ConfigCompatibleWithStandardLibrary

    rows, err := db.Queryx(`SELECT title, language, ranking, slug, search_term, logo_url FROM public.news_newspaper`)
    if err != nil {
        log.Println(err)
    }

    defer rows.Close()
    tableData := make([]map[string]interface{}, 0)

    for rows.Next() {
        entry := make(map[string]interface{})
        err := rows.MapScan(entry)
        if err != nil {
            log.Println(err)
        }
        tableData = append(tableData, entry)
    }

    jsonData, _ := json.Marshal(tableData)

    fmt.Println(string(jsonData))  // printing expected json
    err = rows.Err()
    if err != nil {
        panic(err)
    }
    return jsonData
}

func (n *NewsPaperController) GetList(c *gin.Context) {
    value := database.GetNewsPapers()
    c.JSON(http.StatusOK, value)
}

问题是我得到的是 base64 字符串作为响应,而不是我期望的 json 对象。如果我将 value 转换为如下所示的字符串,我将获得人类可读的值 .

c.JSON(http.StatusOK, string(value))

但整个响应编码为这样的字符串:

"[{\"language\":\"en\",\"logo_url\":\"..\",\"ranking\":2,\"search_term\":\"..\",\"slug\":\"..\",\"title\":\"....\"}]

如何获得如下 json 响应:

 [{"language":"en","logo_url":"..","ranking":2,"search_term":"..","slug":"..","title":".."} ] 

func (c *Context) JSON(code int, obj interface{})

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

c.JSON() 序列化为 JSON 你不需要在使用前解组。在 c.JSON()

中使用 tableData
func GetNewsPapers()  []map[string]interface{}{
    // your existing code
    return tableData
}

func (n *NewsPaperController) GetList(c *gin.Context) {
    value := database.GetNewsPapers()
    c.JSON(http.StatusOK, value)
}

并且使用 %#v 你可以看到值的 Go 语法表示,你也可以在其中找到转义字符

fmt.Printf("%#v", string(jsonData))