JSON Toolkit

JSON to Go Struct: The Generator Gives You a Skeleton, These Four Things Need Hands

Bottom line: Paste an API response sample into a converter and get tagged Go structs in seconds — but numbers land as float64, optional fields never become pointers automatically, omitempty cannot drop empty structs, and most date strings never become time.Time. This guide gives the full mapping table, the pointer-versus-omitzero trade-off, and a four-step checklist to finish the generated code.

Intermediate~6 min readPublished 2026-11-22Updated 2026-11-22
Converting a JSON sample into Go struct code with an online converter

The bottom line: the structs a converter produces in ten seconds will compile, but they are not production-ready. A generator only describes the single sample you pasted in — numbers become float64, optional fields never become pointers on their own, omitempty cannot drop empty structs, and most date strings stay strings. Those four gaps remain your job after pasting.

Turning an API response into Go structs is pure mechanical work, and the cost of mechanical work hides in silence: a misspelled field name produces no compile error, just a field that stays zero forever; one wrong switch on null handling and "note": null appears in production responses where nobody expected it. Generating structs solves the name-and-type alignment problem, but two things never align themselves: the variants outside your sample, and the gap between Go's type system and JSON's.

What the Generator Actually Reads: A Mapping Table

Every JSON → Go converter runs on the same mapping table. Run a typical order response through this site's /convert/go page — paste the sample, enable json tags — and you get this shape:

JSON value Generated Go type Notes
string string Date strings usually stay strings, see time.Time below
integer float64 encoding/json parses numbers as doubles internally
decimal float64 Swap money fields to a decimal library or int64 minor units
true / false bool No traps
null any One null sample proves nothing, conservative fallback
object named struct Nested objects become their own struct
empty object {} map[string]any No fields to observe, generators don't guess
array []ElementType Element type inferred from the first sample
mixed types any Go has no union types, multi-type fields fall back
// Input sample
// {"id":"A-1029","items":[{"sku":"J-01","qty":2}],"coupon":null}
type Root struct {
  ID     string `json:"id"`
  Items  []Item `json:"items"`
  Coupon any    `json:"coupon"`
}

type Item struct {
  Sku string `json:"sku"`
  Qty int    `json:"qty"`
}

Three observations. The nested items object became its own Item struct referenced through a slice. coupon only ever appeared as null, so the generator cannot prove what it will be later and falls back to any. The number qty lands as int or float64 depending on the tool — the strategies differ, but they all rest on the same assumption: the sample is the whole truth.

json Tags: Original Names, Options, and Three Easy Misses

Tags carry the highest information density in the generator's output and are also the easiest part to get subtly wrong. The rules come straight from the encoding/json documentation:

Field int `json:"myName"`            // appears under key myName
Field int `json:"myName,omitempty"`  // whole field omitted when empty
Field int `json:",omitempty"`        // default field name, option only
Field int `json:"-"`                 // always ignored, no encode/decode
Field int64 `json:"id,string"`       // number encoded inside a string

Three misses worth memorizing. First, the leading comma in json:",omitempty" — when you only want empty-value skipping without renaming the key, the comma is mandatory; without it the field is treated as a key literally named ,omitempty. Second, keep the original JSON key in the tag (user_id, html_url) while the Go field uses idiomatic casing (UserID, HTMLURL): without a tag, matching uses the field name verbatim, so a response key of userId silently never maps. Third, json:"-" ignores the field, but json:"-," means the key really is named -.

Pointers: nil Is the Only Way to Distinguish "Absent" from "Zero"

Go's zero-value system makes int and string incapable of expressing "field not present" — 0 and "" might be real data or might be unparsed. The same JSON key has three states: present with a value, present as null, and absent. Value types cover only the first.

type Config struct {
  Note    string  `json:"note,omitempty"`   // omitted only when exactly ""
  Alias   *string `json:"alias,omitempty"`  // omitted when nil
  Details *Meta   `json:"details,omitempty"`
}

A pointer field's zero value is nil. json.Unmarshal leaves it nil when the key is missing or null, and omitempty skips it only then. That is why most converters offer a "use pointers for nested objects" switch: enabled, nested structs become *Item, and in a PATCH request "field not sent" and "sent null to delete" finally separate. The price is nil checks everywhere — p.Address.Street panics when Address is nil, one of the most common runtime crashes in Go JSON code.

The Empty Struct omitempty Cannot Drop, and the Hole omitzero Fills

The official omitempty definition works on values: false, 0, nil pointers, nil interfaces, and arrays, slices, maps, or strings of length zero. Note what is not on the list: empty structs.

type Order struct {
  Meta Meta `json:"meta,omitempty"`
}
type Meta struct {
  Version string
  Build   int
}

// Meta{Version: "1.0"} → "meta":{"version":"1.0","build":0}
// Meta{}              → "meta":{}   ← omitempty did nothing

A struct field is never omitted by omitempty — it lives in memory as a fixed-size container, and an existing container is not "empty". The fix is turning the field into *Meta; only a nil pointer gets dropped. Since Go 1.24 there is a second switch, omitzero: judged by the Go zero value, calling IsZero() bool on the type when it defines one, which is the only way a zero time.Time gets omitted. With encoding/json/v2 (experiment in Go 1.25) the semantics shift again — v2's omitempty judges the encoded JSON result (only null, "", {}, [] count as empty), so count: 0 stays in the output; when migrating old code, omitempty on bool and number fields must become omitzero to keep the old meaning.

Every Number Becomes float64: The Big-Integer Trap

When no explicit type is declared, encoding/json's decoder treats numbers as float64, and float64 has only 53 significand bits. The classic JavaScript case — 9007199254740993 turning into 9007199254740992 — exists in Go too, as long as the target field is float64 or any.

var v map[string]any
_ = json.Unmarshal([]byte(`{"id":9007199254740993}`), &v)
// v["id"] is float64(9007199254740992), precision already lost

Three ways out. Declare the struct field as int64 and the decoder parses exactly into it. When you must go through any, call decoder.UseNumber() so numbers land as json.Number strings you convert deliberately. Never use floating point for money — store minor units in int64 or use a decimal library. Whenever an API returns snowflake IDs or 64-bit order numbers, this section is a mandatory check.

time.Time Only Accepts RFC 3339

Given "2024-01-15T10:30:00Z" a generator maps time.Time; given "2024-01-15 10:30:00" it leaves a string. That is not laziness — it is a hard constraint of encoding/json: time.Time implements UnmarshalJSON and parses strictly in the RFC 3339 layout 2006-01-02T15:04:05Z07:00. Missing T, missing zone, or a Z followed by an offset all fail:

parsing time "\"2022-07-27T14:16:00Z04:00\"" as
"\"2006-01-02T15:04:05Z07:00\"": cannot parse "04:00\"" as "\""

When the upstream format cannot change, the standard fix is a custom type wrapping time.Time whose UnmarshalJSON tries several layouts:

type CustomDate struct{ time.Time }

func (c *CustomDate) UnmarshalJSON(b []byte) error {
  s := strings.Trim(string(b), `"`)
  t, err := time.Parse("2006-01-02 15:04:05", s)
  if err != nil {
    t, err = time.Parse(time.RFC3339, s)
    if err != nil {
      return fmt.Errorf("invalid date format: %w", err)
    }
  }
  c.Time = t
  return nil
}

The Four-Step Checklist After Generating

Four steps separate generator output from production code, and walking them once is cheaper than debugging later:

  1. Replace every any fallback: search for any, revisit three to five real samples per fallback field, then land on a concrete type or a pointer;
  2. Re-check number widths: move IDs, amounts, and counters from float64 to int64 / int32 / decimal; when unsure of the width, write int64;
  3. Mark optionality: pointer fields or omitempty/omitzero for array-item fields, PATCH bodies, and nullable third-party API fields — decide the nil semantics once, here;
  4. Compile and round-trip: run go vet, then add a Marshal→Unmarshal round-trip test to lock the wire format — this catches the behavior drift that future encoding/json upgrades introduce.

From Sample to Contract: The Converter's Boundary

A converter answers "what does this sample look like", not "what will this interface always look like". Competing tools say it plainly in their own docs: one sample cannot prove production variants — optionality, time formats, and enum values all need human review. So build the habit: before pasting, gather the responses most likely to expose differences (empty list, all fields, one with nulls); after generating, treat the output as a draft, not a deliverable. If the interface has a contract document, make the constraints explicit with JSON Schema and align the generated code to it — that beats inferring from samples by an order of magnitude. For the cross-language view of the same problem, the Java side is covered in our JSON-to-Java generator field test, the frontend contract in JSON to TypeScript interfaces; the numeric-precision gap reappears in every language wearing a different costume, detailed in the JSON big-number precision trap.

Which fields still need manual review after generating?

At least four: any fallbacks, number widths (float64 → int64), pointer-izing optional fields, and whether date fields should be string or time.Time. All four are production variants invisible in the sample; generators don't guess, humans must.

Why is my field still in the JSON after adding omitempty?

omitempty only skips zero values: false, 0, "", nil, empty slices. An empty struct {} is not a zero value, so it survives — change the field to a pointer type. A zero time.Time needs omitzero, not omitempty.

Why did my big integer ID change after unmarshaling?

Without an explicit type, encoding/json parses numbers as float64, which carries 53 significand bits; integers past 2^53 lose precision. Type the field int64, or call UseNumber() to keep numbers as json.Number.

When should a nested object field be a pointer?

Two cases: the field may be absent or null (nil separates "not sent" from "zero value"), and PATCH requests must distinguish "not submitted" from "submitted null to delete". For ordinary response structs with non-nullable fields, value types are safer — pay the nil-check cost only when you actually need the distinction.