I am trying to show on html a json array but I need to put a name before the var:
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
var mjson []model.Author
db, err := sql.Open("mysql", "root:@tcp(localhost)/bibliotecagnommo")
if err != nil {
fmt.Println(err)
}
datos, err2 := db.Query("SELECT * FROM author;")
if err2 != nil {
fmt.Println(err2)
}
for datos.Next() {
var id, nombre, apellido string
err3 := datos.Scan(&id, &nombre, &apellido)
if err3 != nil {
fmt.Println(err3)
}
autor := new(model.Author)
autor.Id = id
autor.FirstName = nombre
autor.LastName = apellido
//autorJsonString := string(autorJson);
mjson = append(mjson, *autor)
}
c.JSON(200, gin.H{
//This line of code "wordToAvoid":mjson,
})
})
r.Run()
}
There is a way to avoid putting a word before that?
Because when I print the var on html it shows the word I putted.
Thanks!
Just replace
c.JSON(200, gin.H{
//This line of code "wordToAvoid":mjson,
})
with
c.JSON(200, mjson)
NOTE: gin.H
has type map[string]interface{}
, so you need to pass a map
i.e. a key is mandatory there. But if you see, the method JSON accepts int
and interface{}
, so just pass an interface{} i.e. your object mjson
.