我正在尝试在 html 上显示一个 json 数组,但我需要在 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()
}
有办法避免在此之前输入一个词吗?因为当我在 html 上打印 var 时,它会显示我输入的单词。
最佳答案
只需更换
c.JSON(200, gin.H{
//This line of code "wordToAvoid":mjson,
})
和
c.JSON(200, mjson)
注意:
gin.H
有类型 map[string]interface{}
,所以你需要传递一张 map 即那里必须有一个 key 。但是如果你看到了,JSON 方法接受
int
和 interface{}
,所以只需传递一个接口(interface){},即您的对象 mjson
.
关于go - 返回值时 map 文字中缺少键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60639844/