亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號