为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
Cats萌萌 2023-01-03 10:01:31
我在 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);
查看完整描述

2 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

您需要实现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)

}


查看完整回答
反对 回复 2023-01-03
?
千万里不及你

TA贡献1784条经验 获得超9个赞

从 Batchers_page_db 中选择 JSON_EXTRACT(userInformation,'$.name') 作为 profileName, JSON_EXTRACT(userInformation,'$.points') 作为 userPoints

未经测试,但类似这样的方法会起作用,但请确保您的数据库字段必须是 JSON 类型。


查看完整回答
反对 回复 2023-01-03
  • 2 回答
  • 0 关注
  • 287 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号