Go Reference
Run Go examples for optional JSON fields, strict decoding, and deterministic map comparisons.
Run the examples
Install Go 1.21 or newer. Save each program as main.go and run go run main.go. No external modules are required.
Distinguish a missing field from zero
For a fresh struct, a pointer field stays nil when the JSON field is absent. A supplied zero produces a non-nil pointer to zero.
package main
import (
"encoding/json"
"fmt"
)
type Config struct {
Port *int `json:"port"`
}
func main() {
for _, input := range []string{"{}", `{"port":0}`} {
var config Config
if err := json.Unmarshal([]byte(input), &config); err != nil {
panic(err)
}
if config.Port == nil {
fmt.Println("port missing or null")
} else {
fmt.Println("port:", *config.Port)
}
}
}Expected output
port missing or null
port: 0Common mistake
A pointer alone does not distinguish an absent field from explicit JSON null. Both produce nil in a fresh struct.
Reject unknown fields and trailing JSON
Use DisallowUnknownFields for a struct destination. After the first successful decode, a second decode must return io.EOF when exactly one JSON value is expected.
package main
import (
"encoding/json"
"fmt"
"io"
"strings"
)
func accepted(input string) bool {
decoder := json.NewDecoder(strings.NewReader(input))
decoder.DisallowUnknownFields()
var config struct { Port int `json:"port"` }
if err := decoder.Decode(&config); err != nil {
return false
}
var extra any
return decoder.Decode(&extra) == io.EOF
}
func main() {
fmt.Println(accepted(`{"port":80}`))
fmt.Println(accepted(`{"port":80,"unknown":true}`))
fmt.Println(accepted(`{"port":80} {"port":81}`))
}Expected output
true
false
falseCommon mistake
DisallowUnknownFields does not reject duplicate keys. For exactly one JSON value, also check for trailing data.
Report changed map values in a stable order
Use the comma-ok lookup to restrict the comparison to keys in both maps. Sort the report after iterating because Go map iteration order can vary.
package main
import (
"fmt"
"slices"
)
func main() {
before := map[string]int{"port": 80, "retries": 3, "timeout": 10}
after := map[string]int{"port": 8080, "timeout": 0}
var changed []string
for key, old := range before {
if current, ok := after[key]; ok && current != old {
changed = append(changed, key)
}
}
slices.Sort(changed)
fmt.Println(changed)
}Expected output
[port timeout]Common mistake
A lookup of a missing integer key yields 0. Check the presence flag before treating it as an explicit zero.