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/json only marshals exported (capitalized) fields, and your JSON keys are usually snake_case — so every field needs a json:"key" tag or the data silently doesn’t map (zero values everywhere).
  • Numbers default to float64. Decoding an arbitrary number into interface{} gives float64. In a typed struct, pick int or int64 for IDs to avoid precision surprises with large values.
  • Nullable fields → pointers. A JSON null into an int gives 0, indistinguishable from a real zero. Use *int (or sql.NullInt64) when you must tell “absent” from “zero”.
  • omitempty for optional output. Add ,omitempty to 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.

Related articles