猿问

如何从 golang 访问 mysql db 中的 JSON 列

我在 mysql 中有一个表,其中包含 3 列配置文件字符串、userInformation JSON、徽章字符串。


轮廓  用户信息    徽章

https://ps.w.org/metronet-profile-picture/assets/icon-256x256.png?rev=2464419   {"name": "Suzan Collins", "points": 10000, "countryName": "波兰"} 资产/batcherPage/gold.png

这是我的结构:


type BatchersData struct {

    ProfileURL      string          `json:"profileUrl"`

    UserInformation UserInformation `json:"userInformation"`

    Badge           string          `json:"badge"`

}

type UserInformation struct {

    Points      int64  `json:"points"`

    Name        string `json:"name"`

    CountryName string `json:"countryName"`

}


我想要做的是在此表上进行选择查询,即 GET 并检索所有信息..


使用此代码,我访问了 Profile 和 Badge :


func getBatchers(c *gin.Context) {


    var batchers []BatchersData

    rows, err := db.Query("SELECT profileUrl, badge FROM Batchers_page_db")


    if err != nil {

        return

    }

    defer rows.Close()

    for rows.Next() {

        var batcher BatchersData

        if err := rows.Scan(&batcher.ProfileURL, &batcher.Badge); err != nil {

            return

        }

        batchers = append(batchers, batcher)

    }

    if err := rows.Err(); err != nil {

        return

    }

    c.IndentedJSON(http.StatusOK, batchers)

}

但我也想访问 JSON 列,即 UserInformation。我知道查询将是


rows, err := db.Query("SELECT * FROM Batchers_page_db")

但我必须更改此声明


if err := rows.Scan(&batcher.ProfileURL, &batcher.Badge);

我试过这样做:但没有任何效果


rows.Scan(&batcher.ProfileURL,&batcher.UserInformation, &batcher.Badge);


Cats萌萌
浏览 289回答 2
2回答

一只萌萌小番薯

您需要实现Scan接口文档以将数据映射到 JSON。在这里试试这个:func (u * UserInformation) Scan(value interface{}) error {  b, ok := value.([]byte)  if !ok {    return errors.New("type assertion to []byte failed")  }  return json.Unmarshal(b, &u)}

千万里不及你

从 Batchers_page_db 中选择 JSON_EXTRACT(userInformation,'$.name') 作为 profileName, JSON_EXTRACT(userInformation,'$.points') 作为 userPoints未经测试,但类似这样的方法会起作用,但请确保您的数据库字段必须是 JSON 类型。
随时随地看视频慕课网APP

相关分类

Go
我要回答