Go Gin converting json response to base64

huangapple go评论79阅读模式
英文:

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)) // 打印预期的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":".."}]
英文:

I am trying to send db query data as json response . Here is my 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
}

and

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

Problem is I am getting base64 string as response not the json object I am expecting. If I convert value to string like below, I get human readable values .

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

But whole response encoded in string like this:

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

How do I get json response like below:

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

答案1

得分: 1

// func (c *Context) JSON(code int, obj interface{}) 
//
// JSON将给定的结构体序列化为JSON,并将Content-Type设置为"application/json"。
//
// 在c.JSON()中使用`tableData`,无需在使用之前进行解组。

func GetNewsPapers() []map[string]interface{} {
    // 你现有的代码
    return tableData
}

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

// 使用`%#v`可以查看值的Go语法表示,其中也包含转义字符

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

希望这个翻译对你有帮助!如果你有任何其他问题,请随时问。

英文:

> 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() serialize as JSON you don't need to unmarshal before use it. Use tableData in 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)
}

And using %#v you can see Go-syntax representation of the value where you will found the escape character also

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

huangapple
  • 本文由 发表于 2020年5月17日 12:47:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61847115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定