Skip to Content
Skip to content
Why Unexported Go Struct Fields Stay Empty in encoding/json
Beginner
Tutorials

Why Unexported Go Struct Fields Stay Empty in encoding/json

Fix Go structs that decode to zero values in json.Unmarshal and catch misspelled JSON keys with DisallowUnknownFields. After this, JSON decoding fails loudly instead of silently dropping data.

Updated 5 min read GoAPIs and Integrations

Skip ahead: If you already capitalize exported struct fields, skip to "Case 2: distinguish omitted from zero with *int" or "Case 4: large integer IDs in map[string]any".

json.Unmarshal returns nil error, your JSON has "port": 8080, and yet cfg.port stays 0. Go did not hit a bug—it silently skipped the lowercase struct field because packages outside yours cannot reflect on unexported fields. That same quiet behaviour shows up with misspelled keys, omitted-vs-zero updates, and large 64-bit IDs. Verified on golang:trixie (Go 1.27.4).

Case 1: lowercase fields stay at zero without an error

package main

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

type BrokenConfig struct {
	Host string `json:"host"`
	port int    `json:"port"`
}

type FixedConfig struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

func main() {
	raw := []byte(`{"host":"127.0.0.1","port":8080}`)

	var b BrokenConfig
	_ = json.Unmarshal(raw, &b)
	fmt.Printf("broken: %+v\n", b)

	var f FixedConfig
	_ = json.Unmarshal(raw, &f)
	fmt.Printf("fixed:  %+v\n", f)

	dec := json.NewDecoder(bytes.NewReader([]byte(`{"host":"127.0.0.1","prot":8080}`)))
	dec.DisallowUnknownFields()
	if err := dec.Decode(&f); err != nil {
		fmt.Println("typo error:", err)
	}
}
broken: {Host:127.0.0.1 port:0}
fixed:  {Host:127.0.0.1 Port:8080}
typo error: json: unknown field "prot"

In BrokenConfig, port starts with a lowercase letter, so encoding/json ignores it completely—even with the `json:"port"` tag present. Capitalizing it to Port lets the decoder populate 8080.

Go's visibility rules apply to reflection just like normal function calls: because encoding/json lives in a different package, it cannot write to unexported fields. And by default, json.Unmarshal also ignores unknown keys like "prot"; switching to json.NewDecoder with dec.DisallowUnknownFields() catches typos immediately.

Case 2: distinguish omitted from zero with *int

In a PATCH endpoint or config override, you often need to know whether the caller left port out or explicitly sent "port": 0. A plain int holds 0 in both cases; a pointer *int stays nil when omitted:

package main

import (
	"encoding/json"
	"fmt"
)

type Patch struct {
	Port *int `json:"port"`
}

func main() {
	for _, raw := range []string{`{}`, `{"port":0}`, `{"port":8080}`} {
		var p Patch
		_ = json.Unmarshal([]byte(raw), &p)
		if p.Port == nil {
			fmt.Printf("%s -> omitted (nil)\n", raw)
		} else {
			fmt.Printf("%s -> provided (%d)\n", raw, *p.Port)
		}
	}
}
{} -> omitted (nil)
{"port":0} -> provided (0)
{"port":8080} -> provided (8080)

Case 3: omitempty drops zero values when encoding

When marshaling structs back to JSON, adding omitempty skips any field whose value is its type's zero value (0, false, "", nil). That surprises people when "stock": 0 or "active": false disappears from an API response.

Case 4: large integer IDs lose precision in map[string]any

If you decode untyped JSON into map[string]any, encoding/json turns every number into float64, which only represents integers exactly up to 2^53. Calling dec.UseNumber() keeps exact digits as json.Number:

package main

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

type Product struct {
	Name  string `json:"name"`
	Stock int    `json:"stock,omitempty"`
}

func main() {
	raw := `{"id":9007199254740993}`
	var plain map[string]any
	_ = json.Unmarshal([]byte(raw), &plain)
	fmt.Printf("float64 any: %.0f\n", plain["id"])

	dec := json.NewDecoder(strings.NewReader(raw))
	dec.UseNumber()
	var exact map[string]any
	_ = dec.Decode(&exact)
	fmt.Printf("UseNumber:   %s\n", exact["id"])

	out, _ := json.Marshal(Product{Name: "Bolt", Stock: 0})
	fmt.Printf("omitempty 0: %s\n", out)
}
float64 any: 9007199254740992
UseNumber:   9007199254740993
omitempty 0: {"name":"Bolt"}

Notice 9007199254740993 silently turned into 9007199254740992 under float64—an off-by-one corruption that breaks database lookups and snowflake IDs.

Struct tags and decoder options

OptionEffectWhen to use
`json:"port"`Maps exported Port to JSON key "port"Standard JSON APIs
`json:"-"`Always skips the exported fieldInternal fields (password hashes, internal IDs)
`json:"port,omitempty"`Omits zero values when encodingOptional fields (not when 0 or false is meaningful)
*int / *boolnil when missing, non-nil when presentPATCH payloads distinguishing omitted vs zero
dec.DisallowUnknownFields()Errors on unexpected JSON keysConfig files and strict request bodies
dec.UseNumber()Keeps numbers as exact json.NumberUntyped maps carrying 64-bit IDs or decimals

💡 Tip: Always pass a pointer (&cfg) to json.Unmarshal or dec.Decode. Passing cfg by value returns json: Unmarshal(non-pointer ...).

Common mistakes

  • Ignoring the error returned by json.Unmarshal: discarding err hides syntax errors and type mismatches until downstream fields look mysteriously empty.
  • Putting spaces in struct tags: write `json:"port,omitempty"`, not `json: "port"`—the space after the colon breaks tag parsing silently.

What happens if you skip this

A configuration file with a typo like "prot": 8080 or a lowercase field loads with nil error, leaving Port at 0. The service binds to a random port (:0), or an API drops "stock": 0 and turns 64-bit customer IDs into rounded floats.

Related course: Go for Beginners.

About

Fix Go structs that decode to zero values in json.Unmarshal and catch misspelled JSON keys with DisallowUnknownFields. After this, JSON decoding fails loudly instead of silently dropping data.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
5 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.