Skip to content

Instantly share code, notes, and snippets.

@aimerneige
Created March 26, 2023 11:15
Show Gist options
  • Save aimerneige/5bcf323e9e34f6a300f4b6d3977254e3 to your computer and use it in GitHub Desktop.
Save aimerneige/5bcf323e9e34f6a300f4b6d3977254e3 to your computer and use it in GitHub Desktop.
Gorm datatypes.JSON Example Code
package main
import (
"encoding/json"
"fmt"
"gorm.io/datatypes"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type User struct {
gorm.Model
Name string
Data datatypes.JSON
}
type UserData struct {
Age int `json:"age"`
Mail string `json:"mail"`
}
func main() {
// init sqlite database
db, err := gorm.Open(sqlite.Open("./data.db"), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(&User{})
// create
user1 := User{
Name: "Aimer",
Data: datatypes.JSON(`{"age": 18, "mail": "[email protected]"}`),
}
user2 := User{
Name: "Neige",
Data: datatypes.JSON(`{"age": 19, "mail": "[email protected]"}`),
}
db.Create(&user1)
db.Create(&user2)
// search
var user User
db.Where("data->>'age' = ?", 18).First(&user)
fmt.Printf("%v\n", &user)
// convert datatypes.JSON to JSON:
jsonBytes, _ := user.Data.MarshalJSON()
jsonData := string(jsonBytes)
fmt.Println(jsonData)
// unmarshal
var userData UserData
json.Unmarshal(jsonBytes, &userData)
fmt.Printf("Age: %d, Mail: %s\n", userData.Age, userData.Mail)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment