Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,9 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re
ptr := v.MapRange()
for ptr.Next() {
valMap.SetMapIndex(ptr.Key(), ptr.Value())
if k, ok := ptr.Key().Interface().(string); ok {
d.appendMetaKey(name, k)
}
}
continue
}
Expand Down Expand Up @@ -1293,6 +1296,7 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re

default:
valMap.SetMapIndex(reflect.ValueOf(keyName), v)
d.appendMetaKey(name, keyName)
}
}

Expand Down Expand Up @@ -1801,6 +1805,17 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
return nil
}

// appendMetaKey records a successfully decoded key when metadata is enabled.
func (d *Decoder) appendMetaKey(name, key string) {
if d.config.Metadata == nil || key == "" {
return
}
if name != "" {
key = name + "." + key
}
d.config.Metadata.Keys = append(d.config.Metadata.Keys, key)
}

func isEmptyValue(v reflect.Value) bool {
switch getKind(v) {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
Expand Down
44 changes: 44 additions & 0 deletions mapstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2737,6 +2737,50 @@ func TestDecodeMetadata(t *testing.T) {
}
}

func TestDecodeMetadata_StructToMap(t *testing.T) {
t.Parallel()

type ExampleStruct struct {
ID string `mapstructure:"id"`
Name string `mapstructure:"name"`
Description string `mapstructure:"description"`
Hidden string `mapstructure:"-"`
unexported string
}

input := &ExampleStruct{
ID: "123",
Name: "test",
Description: "desc",
Hidden: "hidden",
unexported: "unexported value",
}

var resultMap map[string]any
var md Metadata
if err := DecodeMetadata(input, &resultMap, &md); err != nil {
t.Fatalf("err: %s", err)
}

wantMap := map[string]any{
"id": "123",
"name": "test",
"description": "desc",
}
if !reflect.DeepEqual(resultMap, wantMap) {
t.Fatalf("bad result: %#v", resultMap)
}

wantKeys := []string{"description", "id", "name"}
sort.Strings(md.Keys)
if !reflect.DeepEqual(md.Keys, wantKeys) {
t.Fatalf("bad keys: %#v", md.Keys)
}
if len(md.Unused) != 0 {
t.Fatalf("bad unused: %#v", md.Unused)
}
}

func TestMetadata(t *testing.T) {
t.Parallel()

Expand Down