How can I access JSON column in mysql db from golang

huangapple go评论70阅读模式
英文:

How can I access JSON column in mysql db from golang

问题

我有一个在MySQL中的表,有3列:Profile字符串、userInformation JSON和badge字符串。

这是我的结构体:

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);
英文:

I have a table in mysql with 3 columns Profile string, userInformation JSON, badge string.

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

This is my struct:

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"`
}

What I want to do is make a select query on this table ie GET and retrieve every information..

using this code, I have accessed Profile and 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)
}

But I want to access JSON column ie UserInformation as well. I know that the query will be

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

But i'll have to make a change in this statement

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

I have tried doing this : but nothing works

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

答案1

得分: 3

你需要实现Scan接口来将数据映射到JSON。试试这个:

func (u *UserInformation) Scan(value interface{}) error {
  b, ok := value.([]byte)
  if !ok {
    return errors.New("类型断言为[]byte失败")
  }
  return json.Unmarshal(b, &u)
}

这段代码将接收一个value参数,并将其转换为[]byte类型。然后,它使用json.Unmarshal函数将value解析为UserInformation结构体。如果类型断言失败,将返回一个错误。

英文:

You need to implement Scan interface doc to map the data to JSON. Here try this:

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)
}

答案2

得分: 0

以下是翻译好的内容:

SELECT JSON_EXTRACT(userInformation,'$.name') as profileName,
JSON_EXTRACT(userInformation,'$.points') as userPoints from
Batchers_page_db

未经测试,但类似这样的代码可以工作,但请确保你的数据库字段必须是 JSON 类型。
英文:

> SELECT JSON_EXTRACT(userInformation,'$.name') as profileName,
> JSON_EXTRACT(userInformation,'$.points') as userPoints from
> Batchers_page_db

Not tested, but something like this will work but make sure your database field must be JSON type.

huangapple
  • 本文由 发表于 2022年7月4日 12:21:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/72851745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定