Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for field name remapping hook #176

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion mapstructure.go
Expand Up @@ -91,6 +91,12 @@ type DecoderConfig struct {
// The tag name that mapstructure reads for field names. This
// defaults to "mapstructure"
TagName string

// Extra transformation methods to match field name from map to struct.
// Options:
// - snake (snake_case: all characters in lower case and concatenating words by '_')
// - kebab (kebab-case: all characters in lower case and concatenating words by '-' )
FieldNameTransFormMethod string
}

// A Decoder takes a raw interface value and turns it into structured
Expand Down Expand Up @@ -1064,7 +1070,16 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
continue
}

if strings.EqualFold(mK, fieldName) {
matched := strings.EqualFold(mK, fieldName)

switch d.config.FieldNameTransFormMethod {
case "snake":
matched = matched || strings.EqualFold(strings.ReplaceAll(mK, "_", ""), fieldName)
case "kabab":
15cm marked this conversation as resolved.
Show resolved Hide resolved
matched = matched || strings.EqualFold(strings.ReplaceAll(mK, "-", ""), fieldName)
}

if matched {
rawMapKey = dataValKey
rawMapVal = dataVal.MapIndex(dataValKey)
break
Expand Down
28 changes: 28 additions & 0 deletions mapstructure_test.go
Expand Up @@ -906,6 +906,34 @@ func TestDecoder_ErrorUnused(t *testing.T) {
}
}

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

input := map[string]interface{}{
"v_string": "WHAT",
}

var result Basic
config := &DecoderConfig{
Result: &result,
FieldNameTransFormMethod: "snake",
}

decoder, err := NewDecoder(config)
if err != nil {
t.Fatalf("err: %s", err)
}

err = decoder.Decode(input)
if err != nil {
t.Fatalf("got an err: %s", err)
}

if result.Vstring != "WHAT" {
t.Errorf("vstring should be WHAT: %#v", result.Vstring)
}
}

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

Expand Down