Free & open source — no account required
Free & open source — no account required
This technical guide provides an in-depth analysis of the json to gorm model engine, best practices for implementation, and data security standards.
GORM is Go's most widely used ORM — it maps Go structs to database tables, handles migrations, and provides a query builder for PostgreSQL, MySQL, SQLite, and SQL Server. When you have a JSON API payload that represents data you want to persist, generating the Go struct gives you the field declarations and json tags instantly. You then add GORM-specific tags and embed gorm.Model to get automatic ID, timestamps, and soft-delete.
// Input JSON (API payload)
{
"name": "Wireless Keyboard",
"sku": "WK-2024-BLK",
"price_usd": 89.99,
"stock_count": 142,
"category": "electronics",
"is_active": true,
"description": null
}
// Generated Go Struct (json tags only)
type Root struct {
Name string `json:"name"`
Sku string `json:"sku"`
PriceUsd float64 `json:"price_usd"`
StockCount float64 `json:"stock_count"`
Category string `json:"category"`
IsActive bool `json:"is_active"`
Description *string `json:"description"`
}
// Refined GORM Model (add gorm tags + embed gorm.Model)
import "gorm.io/gorm"
type Product struct {
gorm.Model // adds ID, CreatedAt, UpdatedAt, DeletedAt
Name string `json:"name" gorm:"not null;size:200"`
SKU string `json:"sku" gorm:"uniqueIndex;not null;size:50"`
PriceUSD float64 `json:"price_usd" gorm:"not null"`
StockCount int `json:"stock_count" gorm:"default:0"` // int not float64
Category string `json:"category" gorm:"index;size:100"`
IsActive bool `json:"is_active" gorm:"default:true"`
Description *string `json:"description" gorm:"type:text"`
}
package main
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"os"
)
func main() {
dsn := os.Getenv("DATABASE_URL")
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
log.Fatal("failed to connect:", err)
}
// AutoMigrate creates or alters the table to match the struct.
// Safe to run on startup: only adds columns/indexes, never drops.
if err := db.AutoMigrate(&Product{}); err != nil {
log.Fatal("migration failed:", err)
}
// Create
product := Product{
Name: "Wireless Keyboard",
SKU: "WK-2024-BLK",
PriceUSD: 89.99,
StockCount: 142,
Category: "electronics",
IsActive: true,
}
db.Create(&product)
log.Printf("Created product ID: %d", product.ID) // gorm.Model adds auto-increment ID
// Read
var found Product
db.First(&found, "sku = ?", "WK-2024-BLK")
log.Printf("Found: %s — $%.2f", found.Name, found.PriceUSD)
// Update specific fields
db.Model(&found).Updates(Product{StockCount: 141, IsActive: true})
// Soft delete (sets DeletedAt, doesn't remove the row)
db.Delete(&found)
// db.Unscoped().Delete(&found) for permanent hard delete
}
type Category struct {
gorm.Model
Name string `json:"name" gorm:"uniqueIndex;not null"`
Products []Product `json:"products" gorm:"foreignKey:CategoryID"`
}
type Product struct {
gorm.Model
Name string `json:"name" gorm:"not null;size:200"`
SKU string `json:"sku" gorm:"uniqueIndex;not null"`
PriceUSD float64 `json:"price_usd" gorm:"not null"`
CategoryID uint `json:"category_id" gorm:"index"`
Category Category `json:"category" gorm:"foreignKey:CategoryID"`
}
// Preload associations when querying
var products []Product
db.Preload("Category").Where("is_active = ?", true).Find(&products)
for _, p := range products {
fmt.Printf("%s (%s) — $%.2f\n", p.Name, p.Category.Name, p.PriceUSD)
}
type Example struct {
gorm.Model
// Column constraints
Name string `gorm:"not null;size:100"` // VARCHAR(100) NOT NULL
Email string `gorm:"uniqueIndex;not null"` // UNIQUE + NOT NULL
Body string `gorm:"type:text"` // TEXT column
Score float64 `gorm:"default:0.0"` // column default
// Index options
Category string `gorm:"index"` // regular index
SKU string `gorm:"uniqueIndex:idx_sku_active"` // named composite index
// Relationships
UserID uint `gorm:"not null;index"` // foreign key column
User User `gorm:"foreignKey:UserID"` // association definition
// Explicit column name (default: snake_case of field name)
FullName string `gorm:"column:full_name"`
}
What does gorm.Model add? Embedding gorm.Model adds four fields automatically: ID uint (auto-increment primary key), CreatedAt time.Time, UpdatedAt time.Time, and DeletedAt gorm.DeletedAt (enables soft-delete). GORM manages all four without manual code. To use a UUID primary key instead, omit gorm.Model and define ID string \`gorm:"primaryKey;default:gen_random_uuid()"\`.
Is AutoMigrate safe to run in production? GORM's AutoMigrate only adds missing columns, indexes, and constraints — it never drops or renames existing columns. This makes it safe to run on startup in most cases. For destructive migrations (dropping columns, renaming), use a migration tool like golang-migrate or goose with explicit SQL files and version tracking.
Should I use float64 for monetary values? No — use github.com/shopspring/decimal for money. Floating-point arithmetic on currency causes rounding errors. Store as DECIMAL(10,2) in the database with the gorm tag gorm:"type:decimal(10,2)".
Is my JSON sent to a server? No. TypeMorph runs entirely in your browser — none of your data leaves your machine.
Is the processing local-only?
Absolutely. TypeMorph operates entirely within your browser's sandbox. We use Web Workers for high-performance computation without ever transmitting your JSON, SQL, or API data to a remote server.
Can I use this for enterprise projects?
Yes. The tool is designed for professional software engineers who require GDPR compliance and data privacy. It is trusted by developers at top-tier startups and financial institutions.