Skip to content

Instantly share code, notes, and snippets.

@jinzhu
Created October 1, 2015 00:07
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jinzhu/4fd1ab15eff169468eae to your computer and use it in GitHub Desktop.
Save jinzhu/4fd1ab15eff169468eae to your computer and use it in GitHub Desktop.
handle postgres json with gorm
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
func main() {
// Setup Postgres - set CONN_STRING to connect to an empty database
db, err := gorm.Open("postgres", "user=gorm DB.name=gorm sslmode=disable")
if err != nil {
panic(err)
}
// db.LogMode(true)
// Create Table
type ClassRoom struct {
gorm.Model
State string `sql:"type:JSONB NOT NULL DEFAULT '{}'::JSONB"`
}
// AutoMigrate
db.DropTable(&ClassRoom{})
db.Debug().AutoMigrate(&ClassRoom{})
// JSON to insert
STATE := `{"uses-kica": false, "hide-assessments-intro": true, "most-recent-grade-skew": 1.5}`
classRoom := ClassRoom{State: STATE}
db.Save(&classRoom)
// Select the row
var result ClassRoom
db.First(&result)
if result.State == STATE {
fmt.Println("SUCCESS: Selected JSON == inserted JSON")
} else {
fmt.Println("FAILED: Selected JSON != inserted JSON")
fmt.Println("Inserted: " + STATE)
fmt.Println("Selected: " + result.State)
}
}
@guotie
Copy link

guotie commented May 12, 2017

mysql的 json类型支持吗

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