gpt4 book ai didi

json - Go Gin将json响应转换为base64

转载 作者:行者123 更新时间:2023-12-01 20:22:21 24 4
gpt4 key购买 nike

我试图发送数据库查询数据作为json响应。这是我的 Controller :

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 thegiven struct as JSON into the response body. It also sets theContent-Type as "application/json".

c.JSON()序列化为JSON,使用前无需解码。在 tableData中使用 c.JSON()
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))

关于json - Go Gin将json响应转换为base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61847115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com