You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Is your feature request related to a problem? Please describe.
I would like to use yaml.DisallowUnknownField() while still be able to perform partial unmarshaling.
Describe the solution you'd like
Describe alternatives you've considered
Additional context
The following snippet just try to perform unmarshaling in two steps:
unmarshal the type
unmarshal the remaining document content based on the type
type T struct {
Type string
Value any
}
type A struct {
Field1 string
}
type B struct {
Field2 string
}
func (t *T) UnmarshalYAML(unmarshal func(interface{}) error) error {
var typ struct{ Type string }
if err := unmarshal(&typ); err != nil {
return fmt.Errorf("error decoding type: %w", err)
}
decodedType := typ.Type
var value any
switch decodedType {
case "a":
value = &A{}
case "b":
value = &B{}
default:
return fmt.Errorf("unknown type %q", decodedType)
}
if err := unmarshal(value); err != nil {
return fmt.Errorf("error decoding value: %w", err)
}
t.Type = decodedType
t.Value = value
return nil
}
var data = `
type: "a"
value:
field1: "field1"
`
func main() {
reader := strings.NewReader(data)
dec := yaml.NewDecoder(reader, yaml.DisallowUnknownField())
t := &T{}
if err := dec.Decode(t); err != nil {
log.Fatal(err)
}
}
If I run this, unfortunately, I get the following error:
The problem is that unmarshal(&typ) looks at the definition of the unnamed structure and see that there are no fields other than Type, so any other field will be treated as unknown, as per yaml.DisallowUnknownField() specification. Is there any solution to this problem?
The text was updated successfully, but these errors were encountered:
Is your feature request related to a problem? Please describe.
I would like to use
yaml.DisallowUnknownField()
while still be able to perform partial unmarshaling.Describe the solution you'd like
Describe alternatives you've considered
Additional context
The following snippet just try to perform unmarshaling in two steps:
type
type
If I run this, unfortunately, I get the following error:
The problem is that
unmarshal(&typ)
looks at the definition of the unnamed structure and see that there are no fields other thanType
, so any other field will be treated as unknown, as peryaml.DisallowUnknownField()
specification. Is there any solution to this problem?The text was updated successfully, but these errors were encountered: