我正在尝试将数据库查询数据作为 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":".."} ]