Skip to content

Conversation

@skaggmannen
Copy link

Description

This pull requests adds a config flag to prevent mapstructure.Decode() from clobbering existing values in nested maps in the destination. Instead, the incoming fields will be merged with existing fields in the destination.

Current behavior example

type Root struct {
	Nested Nested
}

type Nested struct {
	A int
	B int
}

src := A{ Nested: Nested{ A: 42 } }
dst := map[string]any{
	"Nested": map[string]any{
		"A": 123,
		"B": 456,
	},
}

if err := mapstructure.Decode(src, &dst); err != nil {
	panic(err)
}

// dst["Nested"]["A"] is now 42
// dst["Nested"]["B"] no longer exists

New behavior example

type Root struct {
	Nested Nested
}

type Nested struct {
	A int
	B int
}

src := A{ Nested: Nested{ A: 42 } }
dst := map[string]any{
	"Nested": map[string]any{
		"A": 123,
		"B": 456,
	},
}

dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
	MergeIntoExisting: true,
	Result: &dst,
})
if err != nil {
	panic(err)
}

if err := dec.Decode(src); err != nil {
	panic(err)
}

// dst["Nested"]["A"] is now 42
// dst["Nested"]["B"] is still 456

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants