Skip to content

Feature Request: Optional root object name #136

@andreev-fn

Description

@andreev-fn

Currently, when the ErrorUnset option is enabled and the root structure is missing some keys, the error messages include empty quotes, which can be confusing.

There was some related work in #113 to improve error messages for unexpected keys (with ErrorUnused), but the current behavior is inconsistent:

  • For missing keys, the root name is displayed as empty quotes.
  • For unexpected keys, the root object type name is shown.
  • This also becomes awkward with anonymous struct types.

Proposal:

Introduce an additional option to manually specify a root object name.

I’m not entirely sure whether the logic introduced in #113 should remain. If we don’t consider error messages part of the API contract, it might make sense to simplify or remove it (though I’d defer to @jmacd and others on this point). If we want to keep the existing logic, then perhaps we should extend it to missing keys as well for consistency - though that would also change the error messages.

Example:

input := map[string]any{
	"surname": "green",
	"relation": map[string]any{
		"surname": "black",
	},
}

var result struct {
	Name     string `mapstructure:"name"`
	Relation struct {
		Name string `mapstructure:"name"`
	} `mapstructure:"relation"`
}

decoder, _ := NewDecoder(&DecoderConfig{
	ErrorUnset:  true,
	ErrorUnused: true,
	Result:      &result,
})

fmt.Println(decoder.Decode(input))

Actual output:

decoding failed due to the following error(s):

'relation' has invalid keys: surname
'relation' has unset fields: name
'struct { Name string "mapstructure:\"name\""; Relation struct { Name string "mapstructure:\"name\"" } "mapstructure:\"relation\"" }' has invalid keys: surname
'' has unset fields: name

Suggested option:

decoder, _ := NewDecoder(&DecoderConfig{
	ErrorUnset:  true,
	ErrorUnused: true,
	Result:      &result,
	RootName:    "root", // here
})

Desired output:

decoding failed due to the following error(s):

'root.relation' has invalid keys: surname
'root.relation' has unset fields: name
'root' has invalid keys: surname
'root' has unset fields: name

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions