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":".."} ]
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))