postgresqlgogo-gorm

How to insert Data in JSONB Field of Postgres using GORM


I have model like this in

type yourTableName struct {
   Name             string `gorm:"type:varchar(50)" json:"name"`
   Email            string `gorm:"type:varchar(50)" json:"email"`
   FieldNameOfJsonb JSONB  `gorm:"type:jsonb" json:"fieldnameofjsonb"`
}
{
    "name": " james",
    "email": "james@gmail.com",
    "FieldNameOfJsonb": [
        {
            "someField1": "value",
            "someFiedl2": "somevalue",    
        },
        {
            "Field1": "value1",
            "Fiedl2": "value2",
        }
    ],

Solution

  • Just add this below code in Model.go (referenceLink)

    
    import (
        "errors"
        "database/sql/driver"
        "encoding/json"
    )
    
    // JSONB Interface for JSONB Field of yourTableName Table
    type JSONB []interface{}
    
    // Value Marshal
    func (a JSONB) Value() (driver.Value, error) {
        return json.Marshal(a)
    }
    
    // Scan Unmarshal
    func (a *JSONB) Scan(value interface{}) error {
        b, ok := value.([]byte)
        if !ok {
            return errors.New("type assertion to []byte failed")
        }
        return json.Unmarshal(b,&a)
    }
    

    -> reference Link for Marshal, Unmarshal