How to insert Data in JSONB Field of Postgres using GORM

Issue

I have model like this in

  • model.go
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"`
}
  • I want to insert FieldNameOfJsonb as an array of object in postgres using GORM

  • Like given below

{
    "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

  • now you can insert data using DB.Create(&yourTableName)

Answered By – M_x

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.