1

I am querying from postgres using golang, one of the field contains json that can sometimes be NULL

Like this

row := db.QueryRow(
    "select my_string, my_json from my_table where my_string = $1",
   my_id)


var my_string sql.NullString
var myjson MyJsonStruct
err := row.Scan(&my_string2, &myjson)

But I am getting

sql: Scan error on column index 2, name "my_json": unsupported Scan, storing driver.Value type <nil> into type *main.MyJsonStruct

I checked https://godoc.org/database/sql but didn't find sql.NullJson What is a go way of dealing with this situation?

0

1 Answer 1

3

No, there is no sql.json. I think the best way to dealing with json column in db is to implement valuer and scanner. so something like this :

// Scan implements database/sql.Scanner interface
func (m *MyJsonStruct) Scan(src interface{}) error {
    if src == nil {
        return nil
    }
    data, ok := src.([]byte)
    if !ok {
        return errors.New("type assertion to []byte failed")
    }
    var myJsonStruct MyJsonStruct
    if err := json.Unmarshal(data, &myJsonStruct); err != nil {
        return fmt.Errorf("unmarshal myJsonStruct: %w", err)
    }
    *m = myJsonStruct
    return nil
}

// Value implements database/sql/driver.Valuer interface
func (m MyJsonStruct) Value() (driver.Value, error) {
    data, err := json.Marshal(m)
    if err != nil {
        return nil, fmt.Errorf("marshal myJsonStruct: %w", err)
    }
    return data, nil
}

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

2 Comments

The Value interface is uncessary right? If I use json:"my_field_name"
yes, it is unnecessary. only implement it if you need to store value

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.