A generated struct is a hypothesis
Run any JSON-to-Go generator on one response from GET /api/orders and you get a struct that looks finished:
type Order struct {
ID string `json:"id"`
Status string `json:"status"`
Total float64 `json:"total"`
CouponCode string `json:"coupon_code"`
Items []Item `json:"items"`
}
type Item struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
UnitPrice float64 `json:"unit_price"`
}It compiles, it unmarshals the sample, and every tag matches. Then the endpoint sends an order placed without a coupon, and the same struct reports the failure somewhere else entirely: unmarshalling succeeds, and order.CouponCode quietly holds "" — the zero value. Nothing errored; the struct just answered a question nobody asked it.
The fix is to decide, per field, what “not there” means. That decision is invisible in the sample and is exactly what the tags exist to encode:
type Order struct {
ID string `json:"id"`
Status string `json:"status"`
Total float64 `json:"total"`
CouponCode *string `json:"coupon_code,omitempty"`
Items []Item `json:"items"`
}The rest of this guide is about the three places where JSON and Go disagree hard enough to lose data: numbers, absence, and names.
Every number is a float64 somewhere
Go’s encoding/json has a rule that surprises everyone once: when you decode into interface{}, every JSON number becomes a float64. Not “integers become int” — everything. The decoder never saw an integer, because JSON numbers have no integer type; it saw a literal and stored the nearest double.
This is the Go face of the precision problem every JSON tool shares: above 253, consecutive integers map to the same double. A 19-digit order ID unmarshalled into interface{} comes back with different digits, and no struct definition can fix a value that was mangled before it reached the field.
- Typed fields are safe. Unmarshalling into
ID int64 `json:"id"`parses the literal directly into an integer — the float64 detour only happens on theinterface{}path. The struct is not just convenient, it is the precision fix. - Generators see what their parser saw. A tool that runs the sample through
JSON.parse(JavaScript) orUnmarshalintointerface{}has already flattened every number to a double before inference starts. Whether it can emitint64at all depends on whether the parser preserved integrality. - Big IDs want
string. If the ID is wider than 253 and must round-trip exactly, the robust choice is a string field — orjson.NumberwithDecoder.UseNumber, which keeps the original literal untouched.
A generator that marks whole-number fields int64 and mixed ones float64 is doing one real job: telling you which values it watched cross the 253 line. One that emits float64 everywhere is being honest about a parser that threw the information away.
Optional is not nullable, and neither is omitempty
JSON has three states for a key: present with a value, present with null, absent. Go strings, numbers and booleans have one: their zero value. A plain struct field collapses all three JSON states into one, and no tag can un-collapse them, because unmarshalling has already happened by the time any tag would be read.
| Field declaration | Key absent | Key is null | Verdict |
|---|---|---|---|
| Field string `json:"field"` | Field stays at its zero value (") — indistinguishable from a real empty string | Unmarshal error: cannot unmarshal null into string | Correct for values that are always present and never null. |
| Field string `json:"field,omitempty"` | Same as above — omitempty affects marshalling only | Unmarshal error, same as above | A common mistake: omitempty does nothing on unmarshal, and zero values are silently dropped when writing back. |
| Field *string `json:"field,omitempty"` | Field stays nil — you can tell absent from empty | Field is set to nil — null and absent look identical, which is usually the pragmatic choice | The form that matches how APIs actually behave, at the cost of pointer checks. |
The table’s sharpest edge is the middle row: omitempty is a marshalling directive and does nothing at all on the unmarshal side. People add it expecting optionality and get a struct that still errors on null. The pointer in the third row is doing the actual work.
The JSON to Go tool encodes exactly this distinction: a key missing from some samples becomes ,omitempty, a key that is sometimes null becomes a pointer, and the two rules are kept separate on purpose.
omitempty drops zero values, not missing ones
The tag’s actual contract: skip the field when it equals Go’s zero value for its type — 0, "", false, nil, an empty map or slice. That contract has four consequences people meet the hard way:
- It fires on zero values, not just absent keys. A
Count int `json:"count,omitempty"`that legitimately holds0is dropped when you marshal the struct back. The consumer reading the output cannot tell “zero” from “not sent”. falseis a zero value too. Booleans are the worst case, becausefalseis often a meaningful answer rather than an absence. Leave omitempty off boolean fields unless the key really is optional in both directions.- nil and empty slices marshal differently.
[]Item(nil)with omitempty is omitted entirely;[]Item{}serialises as[]. If the API sends"items": [], decide which one your round trip preserves. - Structs are never empty. omitempty has no effect on nested struct values — there is no concept of a zero struct. A nested object that should disappear when empty needs a pointer type.
The rule of thumb that survives contact with real APIs: use omitempty where the key is optional in both directions, use a pointer where “absent” and “zero” must stay distinguishable, and leave both off for fields the endpoint always sends.
Name fields the way Go reads them
Go’s naming convention is the source of one more silent mismatch: the json tag must carry the exact key from the wire, while the field name follows Go style. That is why api_url becomes APIURL and id becomes ID — the golint initialisms list treats URL, API, ID, HTTP and friends as whole words, and a linter will flag ApiUrl in review.
Two failure modes live here. A generator that leaves ApiUrl produces code that fails lint on day one. A generator that forgets the tag entirely — relying on Go’s case-insensitive key match — still works, until someone reorders or renames the field and the JSON key silently stops matching. Always emit the tag, even when it matches the field name: the tag is the contract, the field name is style.
Verify the struct with a round trip
The cheapest test that catches nearly every struct bug is a round trip: unmarshal the real payload into the generated struct, marshal it back, and compare the JSON. Fields that come out missing point at omitempty on zero values; fields that come out renamed point at a wrong tag; values that come out different point at the float64 path.
func TestOrderRoundTrip(t *testing.T) {
raw := []byte(`{"id":"84126","total":19.5,"items":[]}`)
var order Order
if err := json.Unmarshal(raw, &order); err != nil {
t.Fatal(err)
}
out, err := json.Marshal(order)
if err != nil {
t.Fatal(err)
}
// Compare as parsed values, not bytes: key order and
// whitespace are free to differ.
var a, b any
if err := json.Unmarshal(raw, &a); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(out, &b); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(a, b) {
t.Fatalf("round trip changed the data:\n in: %s\nout: %s", raw, out)
}
}Keep one fixture per endpoint — a captured real response, not a hand-written sample — and the test becomes a contract the struct cannot silently break.