How to Unmarshal JSON Into Go Structs: Tags, omitempty, Pointers

Map JSON to Go structs the right way: exported fields, json tags, omitempty, pointers for null, int64 vs float64 and time.Time, with working examples.

Updated September 29, 2026 6 min read

Use the free JSON to Go StructGenerate Go structs with json tags from any JSON sample or API

Every Go service that talks to an API eventually needs a struct for the JSON it receives. Writing one by hand is fine for three fields; for a real response with nested objects, lists and optional keys, it is slow and easy to get subtly wrong. A misspelled tag or an unexported field doesn't cause an error: the value just stays empty, and you find out later.

This guide explains how Go's standard encoding/json package matches JSON keys to struct fields, what the json tag options do, when to use pointers, and which Go type suits each JSON value. It then shows how to generate structs from a sample and what to check before you commit the result.

How encoding/json matches keys to fields

json.Unmarshal decodes a JSON document into a Go value. For structs, it follows a few rules:

  • Only exported fields are set. A field must start with a capital letter (Name, not name). Unexported fields are ignored silently.
  • Tags choose the key. The tag `json:"order_id"` maps the field to the key order_id. Without a tag, the field name itself is used.
  • Matching is case-insensitive as a fallback. If no exact match exists, encoding/json accepts a key that matches ignoring case, so OrderId would also receive orderid. Explicit tags make the mapping unambiguous.
  • Unknown keys are ignored. Extra fields in the JSON are skipped unless you ask the decoder to reject them.
  • Missing keys leave the zero value. If coupon is absent, a string field stays "".

A minimal round trip looks like this:

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Order struct {
	OrderID string  `json:"orderId"`
	Total   float64 `json:"total"`
	Items   int64   `json:"items"`
	Coupon  string  `json:"coupon,omitempty"`
}

func main() {
	data := []byte(`{"orderId":"A-100","total":59.9,"items":3}`)

	var o Order
	if err := json.Unmarshal(data, &o); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", o) // {OrderID:A-100 Total:59.9 Items:3 Coupon:}

	out, _ := json.Marshal(o)
	fmt.Println(string(out)) // {"orderId":"A-100","total":59.9,"items":3}
}

Choosing Go types for JSON values

JSON value Typical Go type Notes
string string Use time.Time for RFC 3339 timestamps if you want parsing
whole number int64 or int A decimal value in the JSON causes an unmarshal error
decimal number float64 Use a decimal library or integer cents for money
true / false bool
object named struct Or map[string]T for dynamic keys
array slice, e.g. []Order
null only / mixed any Decoded as map[string]any, []any, float64 and so on

Two traps deserve attention. First, a sample that happens to contain "total": 12 suggests an integer, but the next response may contain 12.5, and unmarshalling that into int64 fails with an error. Look at more than one example before trusting integer fields. Second, time.Time implements JSON decoding for RFC 3339 strings such as "2024-03-18T09:12:44Z", but not for other formats like "18/03/2024", which need a custom type.

omitempty and pointers: absent, null and zero

JSON distinguishes three states for a field: missing, null, and a value. A plain Go field has only one way to say "nothing", its zero value. That is where tag options and pointers come in.

  • omitempty only affects encoding. When you marshal a struct, a field holding its zero value ("", 0, false, nil, empty slice or map) is left out of the JSON. It does nothing when decoding.
  • A pointer field such as *string stays nil when the key is missing or null, and points to a value when one is present. That lets you tell "no discount" (nil) apart from "discount of 0" (0).

Use pointers when the difference between "not provided" and "zero" matters: partial updates (PATCH requests), optional numeric settings, and nullable database columns. Otherwise plain values are simpler to work with. Note that omitempty does not omit a zero-value struct; only pointer-to-struct fields that are nil disappear.

Generate structs from a JSON sample

The JSON to Go Struct converter writes the struct definitions from a real response, so you only have to review them.

  1. Open JSON to Go Struct and paste a response into JSON sample, click Open file, or use Load sample.
  2. Set Root type name (for example User) and Package.
  3. Keep omitempty on optional fields on to add ,omitempty to keys that are missing from some array items or are null.
  4. Turn on Pointers for nullable fields if you want nullable values as pointer types such as *string.
  5. Review the Go structs output, then Copy it or Download a .go file.

The generator merges all items in an array, so a key that appears in only some objects is recognised as optional. Field names follow Go conventions for common initialisms (orderId becomes OrderID, avatarUrl becomes AvatarURL), whole numbers become int64, decimals float64, and repeated object shapes are merged into a single named struct. For the built-in sample, the order list becomes:

type Order struct {
	OrderID string  `json:"orderId"`
	Total   float64 `json:"total"`
	Items   int64   `json:"items"`
	Coupon  string  `json:"coupon,omitempty"`
}

Timestamps stay as string, and a key that is only ever null in the sample becomes any. Change those by hand once you know the real type.

Other ways to get your structs

  • Write them by hand. Best for small payloads, or when you want custom types from the start.
  • Generate from a schema. If the API publishes an OpenAPI or JSON Schema document, a code generator driven by that contract is more reliable than any sample, because it knows which fields are required. If you only have samples, the JSON Schema Generator can draft a schema to review with the API owner.
  • Decode into map[string]any. Useful for truly dynamic data, but you lose type checking and have to assert types at every access.

If you work in several languages, the same sample can produce TypeScript types, Python classes or C# classes, which keeps models consistent across services. See also how to generate TypeScript types from JSON.

Checks before you commit generated structs

Reject unexpected fields in strict code

To catch API changes early, decode with DisallowUnknownFields:

dec := json.NewDecoder(resp.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&user); err != nil {
	return fmt.Errorf("decode user: %w", err)
}

Watch for large integers

IDs larger than 2^53 survive in int64, but if you ever decode them into any, they become float64 and lose precision. Use dec.UseNumber() or keep such IDs as strings.

Validate the sample first

If the generator reports a parse error, fix the input with the JSON Formatter before generating again.

Frequently asked questions

Why are my struct fields empty after json.Unmarshal?

Usually the fields are unexported (lowercase) or the tag does not match the JSON key. Only exported fields with matching names or tags are filled.

Does omitempty affect unmarshalling?

No. omitempty only controls whether zero values are left out when marshalling. Decoding behaves the same with or without it.

When should I use a pointer field?

When you need to tell a missing or null value apart from a zero value, such as in PATCH requests or optional numeric settings.

How do I parse dates from JSON in Go?

Use time.Time for RFC 3339 timestamps, which encoding/json decodes automatically. Other formats need a custom type with its own UnmarshalJSON method.

Should I use int or int64 for JSON numbers?

int64 is explicit and matches common API IDs; int is 64-bit on most modern platforms. Use float64 for any field that can hold decimals.

Try it now: JSON to Go Struct

Loading tool…