Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Created February 8, 2016 14:49
Show Gist options
  • Select an option

  • Save yanmhlv/d00aa61082d3b8d71bed to your computer and use it in GitHub Desktop.

Select an option

Save yanmhlv/d00aa61082d3b8d71bed to your computer and use it in GitHub Desktop.
JSONB in gorm
package main
import (
"database/sql/driver"
"encoding/json"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type JSONB map[string]interface{}
func (j JSONB) Value() (driver.Value, error) {
valueString, err := json.Marshal(j)
return string(valueString), err
}
func (j *JSONB) Scan(value interface{}) error {
if err := json.Unmarshal(value.([]byte), &j); err != nil {
return err
}
return nil
}
type User struct {
gorm.Model
Info JSONB `sql:"type:jsonb"`
}
func main() {
db, _ := gorm.Open("postgres", "user=myuser password=mypassword dbname=mydbname sslmode=disable")
db.CreateTable(&User{})
db.Create(&User{Info: JSONB{"age": 27, "name": "Yan"}})
}
@VishwasShashidhar

Copy link
Copy Markdown

Thank you! This is very useful.

@kachar

kachar commented Apr 6, 2021

Copy link
Copy Markdown

Awesome! Just what I needed

@kuchaguangjie

Copy link
Copy Markdown

Probably use pgtype.JSONB (from "jackc/pgtype"), is a better solution.

@hewenyu

hewenyu commented Jun 15, 2021

Copy link
Copy Markdown

This is very useful.

@kachar

kachar commented Jun 15, 2021

Copy link
Copy Markdown

Looks like it's a bit outdated as latest gorm version uses different annotation gorm:"type:jsonb" instead of sql:"type:jsonb" and this makes all marshaled values to be null

@bjornmolin

Copy link
Copy Markdown

Thank you so much! 🌷 return string(valueString), err solved my problem with ERROR: invalid input syntax for type json (SQLSTATE 22P02)

I have spent hour if not days in order to find out this

@encryptblockr

Copy link
Copy Markdown

still valid after 7 years? wow

@encryptblockr

encryptblockr commented Aug 7, 2022

Copy link
Copy Markdown

how do we query the JSONB? anyone willing to share their gist on how to do JSONB queries also using GORM?

@kachar @bjornmolin

@tusharf5

tusharf5 commented Jan 1, 2025

Copy link
Copy Markdown

thanks

@kelevro

kelevro commented Oct 2, 2025

Copy link
Copy Markdown

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment