How do I use JSONB columns using GORM?

Using JSONB columns in GORM allows you to work with JSON data types in PostgreSQL seamlessly. With GORM, you can easily define and manipulate JSONB fields in your Go application.

GORM, Go, JSONB, PostgreSQL, ORM, database, handling JSON, Go programming

package main import ( "encoding/json" "gorm.io/driver/postgres" "gorm.io/gorm" ) type User struct { ID uint `gorm:"primaryKey"` Name string `json:"name"` Metadata json.RawMessage `json:"metadata" gorm:"type:jsonb"` // JSONB column } func main() { dsn := "user=gorm dbname=gorm port=9920 sslmode=disable" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect to the database") } // Auto migrate the User structure db.AutoMigrate(&User{}) // Example of inserting a record with JSONB data metadata := map[string]interface{}{ "age": 30, "hobbies": []string{"reading", "gaming"}, } metadataJSON, _ := json.Marshal(metadata) user := User{Name: "John Doe", Metadata: metadataJSON} db.Create(&user) // Example of querying a record var fetchedUser User db.First(&fetchedUser, user.ID) }

GORM Go JSONB PostgreSQL ORM database handling JSON Go programming