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

GO - 将 mysql json 解析为字符串数组

GO - 将 mysql json 解析为字符串数组

Go
阿波罗的战车 2023-01-03 16:46:25
有这样的结构:Programs struct {    ID                  int      `json:"id"`    ShortName           string   `json:"short_name"`    ProgramPoints       float64  `json:"program_points"`    Countries           []string `json:"countries"`}该列countries是 JSON 列,其中包含国家/地区["US","GB"] 解析数组:    stmt, err := db.Query(sql)    err = stmt.Scan(            &program.ID,            &program.ShortName,            &program.ProgramPoints,            &program.Countries)有错误 unsupported Scan, storing driver.Value type []uint8 into type *[]string 我找到了如何将 JSON 对象解析为结构而不是数组的方法。提前感谢任何帮助
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

因此,当您希望 JSON 值来自数据库并自动(取消)编组时,您需要为此创建一个类型:


type Programs struct {

    ID                  int       `json:"id"`

    ShortName           string    `json:"short_name"`

    ProgramPoints       float64   `json:"program_points"`

    Countries           Countries `json:"countries"`

}


type Countries []string


func (c Countries) Value() (driver.Value, error) {

    return json.Marshal(c) // return json marshalled value

}


func (c *Countries) Scan(v interface{}) error {

    switch tv := v.(type) {

    case []byte:

        return json.Unmarshal(tv, &c) // unmarshal

    case []uint8:

        return json.Unmarshal([]byte(tv), &c) // can't remember the specifics, but this may be needed

    }

    return errors.New("unsupported type")

}

那应该处理这些stmt.Scan东西



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

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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