首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将mysql json解析为字符串数组。

将mysql json解析为字符串数组。
EN

Stack Overflow用户
提问于 2022-07-21 09:20:32
回答 1查看 212关注 0票数 1

有这样的结构:

代码语言:javascript
复制
Programs struct {
    ID                  int      `json:"id"`
    ShortName           string   `json:"short_name"`
    ProgramPoints       float64  `json:"program_points"`
    Countries           []string `json:"countries"`
}

countries是包含国家["US","GB"]解析数组的JSON列:

代码语言:javascript
复制
    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 *[]字符串,我找到了如何将JSON解析为struct,而不是数组。提前为您提供任何帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-21 09:46:14

因此,当您希望JSON值来自DB和be (Un)自动封送时,您需要为此创建一个类型:

代码语言:javascript
复制
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的东西

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73063654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档