9

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": "[email protected]",
    "FieldNameOfJsonb": [
        {
            "someField1": "value",
            "someFiedl2": "somevalue",    
        },
        {
            "Field1": "value1",
            "Fiedl2": "value2",
        }
    ],

4 Answers 4

12

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I would change the type to: type JSONB map[string]interface{}
obviously we can change as per our requirement
12

I have answered a similar question in https://stackoverflow.com/a/71636216/13719636 .

The simplest way to use JSONB in Gorm is to use pgtype.JSONB.

Gorm uses pgx as it driver, and pgx has package called pgtype, which has type named pgtype.JSONB.

If you have already install pgx as Gorm instructed, you don't need install any other package.

This method should be the best practice since it using underlying driver and no custom code is needed.

type User struct {
    gorm.Model
    Data pgtype.JSONB `gorm:"type:jsonb;default:'[]';not null"`
}

Get value from DB

u := User{}
db.find(&u)

var data []string

err := u.Data.AssignTo(&data)
if err != nil {
    t.Fatal(err)
}

Set value to DB

u := User{}

err := u.Data.Set([]string{"abc","def"})
if err != nil {
    return
}

db.Updates(&u)

6 Comments

dsnt wok for me
Unfortunately, it doesn't work for me either
any working solution for this?
Metadata pgtype.JSONB json:"-" gorm:"column:metadata" helps.. "type:jsonb" was causing issue for me.. remove it and it works :)
thanks, it worked for me, my type was a slice of int, and used the same code as its above
|
2

You can use gorm-jsonb package.

Comments

2

I was able to make it work by simply adding serializer:json into the struct attribute, like so:

type yourTableName struct {
   Name             string `gorm:"type:varchar(50)" json:"name"`
   Email            string `gorm:"type:varchar(50)" json:"email"`
   FieldNameOfJsonb JSONB  `gorm:"type:jsonb;serializer:json" json:"fieldnameofjsonb"`
}

Comments

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.