Generate Go Structs from JSON (with the Right Tags and Types)
Go’s encoding/json needs a struct to unmarshal into. Here’s how to turn a JSON payload into a correct Go struct — tags, types, and the gotchas that cause silent zero-values.
The fast path
{ "user_id": 1, "full_name": "Ada", "is_active": true }
becomes
type Root struct {
UserID int `json:"user_id"`
FullName string `json:"full_name"`
IsActive bool `json:"is_active"`
}
The JSON to Go converter generates this in your browser — exported field names, with the snake_case keys preserved in the json: tag.
The gotchas
- Exported fields + json tags are mandatory.
encoding/jsononly marshals exported (capitalized) fields, and your JSON keys are usually snake_case — so every field needs ajson:"key"tag or the data silently doesn’t map (zero values everywhere). - Numbers default to
float64. Decoding an arbitrary number intointerface{}givesfloat64. In a typed struct, pickintorint64for IDs to avoid precision surprises with large values. - Nullable fields → pointers. A JSON
nullinto anintgives0, indistinguishable from a real zero. Use*int(orsql.NullInt64) when you must tell “absent” from “zero”. omitemptyfor optional output. Add,omitemptyto a tag to skip zero-value fields when marshalling back out.- Unknown or dynamic keys →
map[string]T. If the keys vary (a dictionary keyed by ID), model it as a map, not a struct.
For a stable API
Generate the struct once, then commit it and hand-tune the numeric types and pointers. Generators nail the shape and tags; they can’t know your nullability or precision needs.