Skip to content
DevTinyTools

Typing

JSON to Go structs: what the tags cannot say

A struct generated from a JSON sample looks finished until the endpoint sends a record that omits a field. Nothing errors; the field just holds a zero value that means nothing. This guide is about the three places where JSON and Go disagree hard enough to lose data, and the tags that let you decide, per field, what “not there” means.

9 min readTool: JSON to Go

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 the interface{} 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) or Unmarshal into interface{} has already flattened every number to a double before inference starts. Whether it can emit int64 at 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 — or json.Number with Decoder.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.

How three Go tag forms behave when a key is absent or null
Field declarationKey absentKey is nullVerdict
Field string `json:"field"`Field stays at its zero value (") — indistinguishable from a real empty stringUnmarshal error: cannot unmarshal null into stringCorrect for values that are always present and never null.
Field string `json:"field,omitempty"`Same as above — omitempty affects marshalling onlyUnmarshal error, same as aboveA 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 emptyField is set to nil — null and absent look identical, which is usually the pragmatic choiceThe 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 holds 0 is dropped when you marshal the struct back. The consumer reading the output cannot tell “zero” from “not sent”.
  • false is a zero value too. Booleans are the worst case, because false is 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.

Frequently asked questions

Why did my generator make every field a float64?
It decoded the sample into interface{} first. encoding/json stores every JSON number as a float64 in that path, so the generator never saw the original integer. A tool that tracks integrality per value — like the JSON to Go tool — can still emit int64; a tool that lost the distinction cannot.
Is it safe to paste a production response into a browser tool?
Only if the tool runs locally. This one parses and generates in the tab, with no network request — you can confirm that in the browser's network panel. Even so, redact tokens and personal data before pasting anything into a page you did not write.
Should I use pointers for every optional field?
Only where absent and zero genuinely differ. Every pointer is a nil check at each call site, and a codebase full of *string is harder to read than one extra empty-string case. The fields worth a pointer are ones where the distinction carries information: a coupon code that was never applied versus one that is empty.
Can Go unmarshal into a struct with extra JSON keys?
Yes — encoding/json ignores keys that have no matching field. That is why a missing key in the sample does not surface until your code reads the field and finds a zero value. It is also why a typo in a tag fails silently: the data is dropped, not rejected.
What is json.Number for?
Decoding numbers without losing precision. When you unmarshal into a map[string]interface{} — or set UseNumber on the decoder — every number arrives as the original literal in a string wrapper. Convert with .Int64() or .Float64() once you know which one it is. For 19-digit IDs that must round-trip exactly, it is the only correct option besides storing them as strings.