Parse JSON into a Struct in Go with json.Unmarshal
Parse JSON into a struct with json.Unmarshal and tags. Unknown keys and unexported fields are skipped without an error, and a type mismatch is reported.
A Go program decodes a JSON document, and a field you expected is empty, with no error to say why.
package main
import (
"encoding/json"
"fmt"
)
type Config struct {
Name string `json:"name"`
Port int `json:"port"`
secret string
}
func main() {
var c Config
err := json.Unmarshal([]byte(`{"name":"web","port":8080,"extra":1,"secret":"x"}`), &c)
fmt.Printf("%+v %v\n", c, err)
var v map[string]any
json.Unmarshal([]byte(`{"port":8080}`), &v)
fmt.Printf("%T\n", v["port"])
err = json.Unmarshal([]byte(`{"port":"8080"}`), &c)
fmt.Println(err)
}{Name:web Port:8080 secret:} <nil>
float64
json: cannot unmarshal string into Go struct field Config.port of type intUnmarshal fills exported fields and matches keys to field names or tags, ignoring case. A key with no matching field (extra) is dropped, and an unexported field (secret) cannot be set by another package, so both vanish without an error, as the first line shows. Into any a JSON number becomes float64, and a string where an int is expected fails with a message that names the field. The rules are in the encoding/json package documentation.
To reject unknown keys, use json.NewDecoder(r) with DisallowUnknownFields(). A field that is absent keeps its zero value, so use a pointer, or a separate boolean, when "missing" and "zero" differ. For numbers that must stay exact, decode with UseNumber() so that a large integer is not rounded to a float.