如何从 Golang 访问 MySQL 数据库中的 JSON 列?

3

我在MySQL中有一张表,有3列,分别是Profile字符串、userInformation JSON和badge字符串。

Profile userInformation badge
https://ps.w.org/metronet-profile-picture/assets/icon-256x256.png?rev=2464419 {"name": "Suzan Collins", "points": 10000, "countryName": "Poland"} assets/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);

不确定MySQL是否支持,但是尝试在运行查询时将JSON列读入字符串,然后有一个单独的步骤将这些字符串中的每个字段解析为json.Unmarshal。 - Ben
也许在查询中进行JSON解析可以解决你的问题?SELECT Profile, userInformation->>name AS name, userInformation->>points AS points, userInformation->>countryName AS countryName, badge FROM Batchers_page_db,然后像这样 rows.Scan(&batcher.ProfileURL, &batcher.name, &batcher.points, &batcher.countryName, &batcher.Badge); - Akina
2个回答

3
你需要实现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)
}

0

选择 JSON_EXTRACT(userInformation,'$.name') 作为个人资料名称,JSON_EXTRACT(userInformation,'$.points') 作为用户积分,从 Batchers_page_db 中获取。

虽然未测试,但类似这样的语句应该可以正常工作,但请确保数据库字段必须是 JSON 类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接