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

有这样的结构:


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 对象解析为结构而不是数组的方法。提前感谢任何帮助


阿波罗的战车
浏览 262回答 1
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 []stringfunc (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东西
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go