Home > Mobile >  GO - parse mysql json to array of strings
GO - parse mysql json to array of strings

Time:07-21

There is such struct:

Programs struct {
    ID                  int      `json:"id"`
    ShortName           string   `json:"short_name"`
    ProgramPoints       float64  `json:"program_points"`
    Countries           []string `json:"countries"`
}

The column countries is JSON column which contains array of countries ["US","GB"] Parsing:

    stmt, err := db.Query(sql)
    err = stmt.Scan(
            &program.ID,
            &program.ShortName,
            &program.ProgramPoints,
            &program.Countries)

Has error unsupported Scan, storing driver.Value type []uint8 into type *[]string I've found the way how to parse JSON object to struct but not array. Thx in advance for any help

CodePudding user response:

So seeing as you're wanting the JSON value to come from the DB and be (un)marshaled automagically, you'll need to create a type for that:

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

That should handle the stmt.Scan stuff

  • Related