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
{{ message }}
This repository was archived by the owner on Jul 22, 2024. It is now read-only.
Repository navigation
This repository was archived by the owner on Jul 22, 2024. It is now read-only.
I think it would be nice if mapstructure would support an unmarshaling interface like for the json module, so custom marshalers can be defined on a per-type basis easily:
typeMyTypestruct {
numberintnumberTimesTwoint
}
// For example we call the interface function for mapstructure UnmarshalMapfunc (t*MyType) UnmarshalMap(valueinterface{}) error {
// Although not a real-world usecase, just multiply our read number by 2.intValue, ok:=value.(int)
if!ok {
returnerrors.New("Can't convert value to int")
}
t.number=valuet.numberTimesTwo=value*2returnnil
}
Specifically I tried to do custom marshaling inside viper, which internally uses mapstructure to unmarshal from its internal map-representation of config-key-values to my config-struct. But there are no possibilities there to "override" marshaling behaviour for my types and I have to write quite some boilerplate to circumvent that^^
Reacted by Maarten Bezemer, Jesper Lindstrøm Nielsen, Beorn Facchini, Guillaume, Elmer Bulthuis, Naga, octalmage, Dale Hui, arminbuerkle, Daniele Vazzola and 31 more
Reacted by Ashwin, Prashant Shahi, Leandro Martins, Eliah Rusin and Alex Goodman
I have the feeling this cannot be done through the existing hooks:
type MapUnmarshaler interface {
UnmarshalMap(interface{}) (interface{}, error)
}
decodeHook := func(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) {
unmarshalerType := reflect.TypeOf((*MapUnmarshaler)(nil)).Elem()
if to.Implements(unmarshalerType) {
// invoke UnmarshalMap by name
in := []reflect.Value{reflect.New(to).Elem(), reflect.ValueOf(v)}
r := to.MethodByName("UnmarshalMap").Func.Call(in)
// get first return parameter and cast reflect.Value
v = r[0].Interface().(interface{})
}
return v, nil
}
This works up to the point where v has the correct type and value. However, DecodeHook is only able to perform input pre-processing.
Furthermore v cannot- even if the hook were able to do more- be returned or assigned to the result value as this would already be of the generic type (the one that that performs the actual decoding) and cannot accept specific implementations.
If you are in a real pinch and are starting out with a map, you can marshal that back to JSON bytes then get it into your known structure. But if you're ingesting JSON, which has a field mapped to arbitrary JSON, you can specify that as a json.RawMessage instead of a map[string]interface{}. This allows custom UnmarshalJSON functions to be triggered.
type StringOrBool bool
func (*sb StringOrBool) UnmarshalJSON(b []byte) error {
...
}
var testMessage struct {
Custom StringOrBool `json:"custom"`
}
raw := json.RawMessage(`{"custom":false}`)
err := json.Unmarshal(raw, &testMessage)
...
I like this suggestion, there is also #204 which overlaps with this by reusing the text unmarshaler. I see a fit for both. If a PR were to open up adding this I would work on merging it, but it hasn't yet!
Note I also merged #183 which should enable this sort of functionality more manually.
For reference, here's an example of a custom unmarshaler interface via the new DecodeHookFuncValue interface. (I'm sure there is a cleaner way to do the structure creation logic than what I did):
typeUnmarshalerinterface {
CustomUnmarshalMethod(interface{}) error
}
funcUnmarshalerHook() mapstructure.DecodeHookFunc {
returnfunc(from reflect.Value, to reflect.Value) (interface{}, error) {
// If the destination implements the unmarshaling interfaceu, ok:=to.Interface().(Unmarshaler)
if!ok {
returnfrom.Interface(), nil
}
// If it is nil and a pointer, create and assign the target value firstifto.IsNil() &&to.Type().Kind() ==reflect.Ptr {
to.Set(reflect.New(to.Type().Elem()))
u=to.Interface().(Unmarshaler)
}
// Call the custom unmarshaling methodiferr:=u.CustomUnmarshalMethod(from.Interface()); err!=nil {
returnto.Interface(), err
}
returnto.Interface(), nil
}
}
Reacted by andig, Vladislav Fursov and Eliah Rusin
Activity
scags9876 commentedon Nov 2, 2018
I would also like mapstructure to support
gopkg.in/guregu/null.v3fields, which I believe fits in with this ticket. The null fields there all implement json.Marshaller. (https://github.com/guregu/null/blob/v3.4.0/bool.go#L94)andig commentedon Jan 14, 2019
Looking at https://github.com/mitchellh/mapstructure/blob/master/mapstructure_test.go#L530 and the
DecodeHookI'm wondering if this is not already implementable by supplying a hook that implements theMapUnmarshalerbehaviour?Have not tried this though.Update
I have the feeling this cannot be done through the existing hooks:
This works up to the point where
vhas the correct type and value. However,DecodeHookis only able to perform input pre-processing.Furthermore
vcannot- even if the hook were able to do more- be returned or assigned to the result value as this would already be of the generic type (the one that that performs the actual decoding) and cannot accept specific implementations.solarfly73 commentedon Jan 15, 2020
If you are in a real pinch and are starting out with a map, you can marshal that back to JSON bytes then get it into your known structure. But if you're ingesting JSON, which has a field mapped to arbitrary JSON, you can specify that as a
json.RawMessageinstead of amap[string]interface{}. This allows custom UnmarshalJSON functions to be triggered.mitchellh commentedon Nov 26, 2020
I like this suggestion, there is also #204 which overlaps with this by reusing the text unmarshaler. I see a fit for both. If a PR were to open up adding this I would work on merging it, but it hasn't yet!
Note I also merged #183 which should enable this sort of functionality more manually.
bored-engineer commentedon Nov 28, 2020
For reference, here's an example of a custom unmarshaler interface via the new
DecodeHookFuncValueinterface. (I'm sure there is a cleaner way to do the structure creation logic than what I did):ghostiam commentedon Feb 8, 2021
Or use stdlib TextUnmarshaler interface
Zed update through "remove mapstructure" by mccanne
Zed update through "remove mapstructure" by mccanne
mthjs commentedon Jun 17, 2022
Is anyone still interested in this?