A config with json tags
The task: read a YAML file into a type that was written for encoding/json,
with json tags and no yaml tags.
The type and the file
// Server is tagged for encoding/json. Timeout also carries a yaml tag.
type Server struct {
ListenAddr string `json:"listen_addr"`
MaxConns int `json:"max_conns,omitempty"`
Timeout int `json:"timeout" yaml:"timeout_s"`
}Full source: docs/examples/decoding/jsontags/example_test.go
const src = `listen_addr: ":8080"
max_conns: 64
timeout_s: 30
`Full source: docs/examples/decoding/jsontags/example_test.go
The default reads the yaml tag alone
var s Server
err := codec.Unmarshal([]byte(src), &s)
fmt.Printf("%+v %v\n", s, err)Full source: docs/examples/decoding/jsontags/example_test.go
{ListenAddr: MaxConns:0 Timeout:30} <nil>Full source: docs/examples/decoding/jsontags/example_test.go
The decode returns no error, and only Timeout is filled. The decoder follows
go.yaml.in/yaml/v3: it reads the yaml tag and nothing else, so
listen_addr and max_conns match no field and are skipped.
A field with no yaml tag takes its Go name in lower case:
var s Server
err := codec.Unmarshal([]byte("listenaddr: \":9090\"\nmaxconns: 8\n"), &s)
fmt.Printf("%+v %v\n", s, err)Full source: docs/examples/decoding/jsontags/example_test.go
{ListenAddr::9090 MaxConns:8 Timeout:0} <nil>Full source: docs/examples/decoding/jsontags/example_test.go
Decode with UseJSONTags
var s Server
err := codec.Unmarshal([]byte(src), &s, codec.UseJSONTags(true))
fmt.Printf("%+v %v\n", s, err)Full source: docs/examples/decoding/jsontags/example_test.go
{ListenAddr::8080 MaxConns:64 Timeout:30} <nil>Full source: docs/examples/decoding/jsontags/example_test.go
UseJSONTags(true) names a field by its json tag wherever the yaml tag
leaves off. The yaml tag still wins: Timeout reads timeout_s, not
timeout.
The option also promotes the fields of an untagged embedded struct, as
encoding/json does, and lets a key match a field name that differs only in
case.
Variations
- Catch the silent miss. Add
codec.DisallowUnknownField(): under the default,listen_addrthen fails the decode. See Reject unknown fields. - No tags at all.
codec.UseInferredNames(true)names an untagged field by its Go name verbatim,ListenAddr, instead oflistenaddr. - The type has an
UnmarshalJSON.UseJSONTagsfills the fields directly and does not call it.codec.UseJSONUnmarshaler()converts the document to JSON and calls it.
The naming rules in full: Struct tags.