Storing Golang JSON into Postgresql

前端 未结 3 1274
深忆病人
深忆病人 2021-02-07 09:57

I want to store a certain struct into my database that has a JSON field within it.

type Comp struct {
    CompId               int64           `db:\"comp_id\" js         


        
相关标签:
3条回答
  • 2021-02-07 10:19

    I don't know how clean of a solution this is but I ended up making my own data type JSONRaw. The DB driver sees it as a []btye but it can still be treated like a json.RawMessage in the Go Code.

    type JSONRaw json.RawMessage
    
    func (j JSONRaw) Value() (driver.Value, error) {
        byteArr := []byte(j)
    
        return driver.Value(byteArr), nil
    }
    
    func (j *JSONRaw) Scan(src interface{}) error {
        asBytes, ok := src.([]byte)
        if !ok {
            return error(errors.New("Scan source was not []bytes"))
        }
        err := json.Unmarshal(asBytes, &j)
        if err != nil {
            return error(errors.New("Scan could not unmarshal to []string"))
        }
    
        return nil
    }
    
    func (m *JSONRaw) MarshalJSON() ([]byte, error) {
        return *m, nil
    }
    
    func (m *JSONRaw) UnmarshalJSON(data []byte) error {
        if m == nil {
            return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
        }
        *m = append((*m)[0:0], data...)
        return nil
    }
    

    This is copy paste reimplementation of MarshalJSON and UnmarshalJSON from the encoding/json library.

    0 讨论(0)
  • 2021-02-07 10:30

    from the go documentation:

    json.RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.
    

    if you log.Printf("%#", colors) in the example provided at package json json.RawMessage you can see that after unmarshalling the json object 'Point'-member isn't unmarshalled but left in []byte format until the color-format is fixed and 'Point' is unmarshalled explicitly.

    Did you try something like unmarshal WeeklySchedule before putting it into the DB?

    0 讨论(0)
  • 2021-02-07 10:31

    sqlx has a type JSONText in github.com/jmoiron/sqlx/types that will do what you need

    doc for JSONText

    0 讨论(0)
提交回复
热议问题