2

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

3
  • Looks alright to me, except for one thing: the field countries is not exported. json.Marshal (and json.Unmarshal) don't handle unexported fields. Change the name to Countries and it should work just fine Commented Jul 21, 2022 at 9:33
  • this is just an typo, the name is already capitalized Commented Jul 21, 2022 at 9:38
  • In that case, you'll need to create a type and implement the Scan method to unmarshal it. The values from SQL are either string or []byte. You'll need to handle it as JSON in a custom callback, I'll post an answer Commented Jul 21, 2022 at 9:40

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.