go - 返回值时 map 文字中缺少键

标签 go go-gin

我正在尝试在 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 方法接受 intinterface{} ,所以只需传递一个接口(interface){},即您的对象 mjson .

关于go - 返回值时 map 文字中缺少键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60639844/

相关文章:

string - 如何从 Golang 中的字符串中修剪 "["字符

sql - 如何停止 golang gc 并手动触发它?

带有 journal_mode=WAL 的 go-sqlite3 给出 'database is locked' 错误

go - 在 gin 路由器中使用现有的 session cookie

go - 如何让多个模型在 gorm 中自动迁移

go - go get命令做缓存吗?

go - 如何使用 Ubuntu 更新 codeanywhere.com 上的 golang

go - Gin 和中间件

go - 如何从 go *gin.context 对象中获取所有查询参数

go - 如何优雅地处理 Web 服务中的错误