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"`
}
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",
}
],
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
DB.Create(&yourTableName)