mapstructure icon indicating copy to clipboard operation
mapstructure copied to clipboard

Encoding does not marshal the fields as expected

Open Laubi opened this issue 2 years ago • 1 comments

According to this comment, encoding should be the arguments reversed. However, the mapstructure annotations are lost and it's not correctly encoded.

Example: https://go.dev/play/p/m1pPpDYYMED

The expected output should have been

{myName:something}

instead of

{Name:something}

Laubi avatar Oct 30 '23 14:10 Laubi

var output any
mapstructure.Decode(foo, &output)

will interpret output as a struct and so when you're done output will be a Foo.

You want:

var output map[string]any
mapstructure.Decode(foo, &output)

Arguably, it would be better if there were two separate functions, Decode[T any](map[string]any, *T) and Encode[T any](*T, map[string]any) so that getting this wrong would be a compile-time error, but that wouldn't be backwards-compatible.

dplepage-dd avatar Oct 30 '23 17:10 dplepage-dd