Struct Tags For JSON And Validation
Drive serialization and validation from one struct tag line so the wire format and the rules are declared in the same place.
Code
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Signup struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"min=8"`
Nickname string `json:"nickname,omitempty"`
}
func validate(s Signup) []string {
var problems []string
if !strings.Contains(s.Email, "@") {
problems = append(problems, "email must contain @")
}
if len(s.Password) < 8 {
problems = append(problems, "password must be at least 8 chars")
}
return problems
}
func main() {
raw := []byte(`{"email":"a@b.c","password":"s3cret-pass","nickname":"ada"}`)
var s Signup
if err := json.Unmarshal(raw, &s); err != nil {
fmt.Println("decode failed:", err)
return
}
fmt.Printf("decoded: %+v\n", s)
fmt.Println("problems:", validate(s))
// omitempty:零值字段不出现在输出里
out, _ := json.Marshal(Signup{Email: "x@y.z", Password: "longenough"})
fmt.Println(string(out))
}Following the data
Struct Tags For JSON And Validation keeps everything in the functions validate and main.
Nothing falls through silently — 1 checkpoint test err != nil on the way through.
Putting it to use
The primary signature is func validate(s Signup) []string
Running the file prints labeled results such as decode failed:, decoded:, problems: — each operation’s effect is visible in the output.
The demo flow inside main is validate — run the file to see it end to end.
Core lines
func validate(s Signup) []string {
var problems []string
if !strings.Contains(s.Email, "@") {
problems = append(problems, "email must contain @")
}
if len(s.Password) < 8 {
problems = append(problems, "password must be at least 8 chars")
}
return problems
}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
FAQ
- What does Struct Tags For JSON And Validation print when run?
- Running the file directly is enough — expect labeled output lines such as `decode failed:`, `decoded:`, `problems:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.