Boone Putney bio photo

Boone Putney

Software Development
Random Musings
Austin, Texas

HumanPlanet Soleer

Email LinkedIn Github

The Golang Gorm package is an excellent ORM library for Golang. We’re utilizing gorm with the Pure Go Postgres driver.

Out of the box Gorm doesn’t include support for the JSONB field type implemented in PostgreSQL 9.4. However, you can pretty painlessly define your own struct type, and write Value() and Copy() functions for this type. Below is an example.

JSONB type Definition

type JSONB map[string]interface{}

Model Definition

type UserAttribute struct {
	ID      int64               
	Data    JSONB   `sql:"type:jsonb"`
}

Value() & Copy() examples:

 1 func (j JSONB) Value() (driver.Value, error) {
 2 	valueString, err := json.Marshal(j)
 3 	return string(valueString), err
 4 }
 5 
 6 func (j *JSONB) Scan(value interface{}) error {
 7 	if err := json.Unmarshal(value.([]byte), &j); err != nil {
 8 		return err
 9 	}
10 	return nil
11 }

Usage

Now, when interacting with JSONB Fields via Gorm, the values are automatically marshalled and unmarshalled.