Created
February 8, 2016 14:49
-
-
Save yanmhlv/d00aa61082d3b8d71bed to your computer and use it in GitHub Desktop.
JSONB in gorm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}}) | |
} |
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
still valid after 7 years? wow
how do we query the JSONB? anyone willing to share their gist on how to do JSONB queries also using GORM?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks like it's a bit outdated as latest gorm version uses different annotation
gorm:"type:jsonb"
instead ofsql:"type:jsonb"
and this makes all marshaled values to benull