Skip to content

Commit

Permalink
Fix embedded struct marshalling
Browse files Browse the repository at this point in the history
  • Loading branch information
alecsammon committed Jul 3, 2024
1 parent e127e90 commit 5579d0b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
5 changes: 3 additions & 2 deletions sheriff.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ func Marshal(options *Options, data interface{}) (interface{}, error) {
field := t.Field(i)
val := v.Field(i)

jsonTag, jsonOpts := parseTag(field.Tag.Get("json"))
jsonTagVal, jsonTagExists := field.Tag.Lookup("json")
jsonTag, jsonOpts := parseTag(jsonTagVal)

// If no json tag is provided, use the field Name
if jsonTag == "" {
Expand Down Expand Up @@ -194,7 +195,7 @@ func Marshal(options *Options, data interface{}) (interface{}, error) {
// when a composition field we want to bring the child
// nodes to the top
nestedVal, ok := v.(KVStore)
if isEmbeddedField && ok {
if !jsonTagExists && isEmbeddedField && ok {
nestedVal.Each(func(k string, v interface{}) {
dest.Set(k, v)
})
Expand Down
29 changes: 23 additions & 6 deletions sheriff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,14 +579,20 @@ type TestMarshal_Embedded struct {
Foo string `json:"foo" groups:"test"`
}

type TestMarshal_NamedEmbedded struct {
Qux string `json:"qux" groups:"test"`
}

type TestMarshal_EmbeddedParent struct {
*TestMarshal_Embedded
Bar string `json:"bar" groups:"test"`
*TestMarshal_NamedEmbedded `json:"embedded"`
Bar string `json:"bar" groups:"test"`
}

func TestMarshal_EmbeddedField(t *testing.T) {
v := TestMarshal_EmbeddedParent{
&TestMarshal_Embedded{"Hello"},
&TestMarshal_NamedEmbedded{"Big"},
"World",
}
o := &Options{Groups: []string{"test"}}
Expand All @@ -597,13 +603,24 @@ func TestMarshal_EmbeddedField(t *testing.T) {
actual, err := json.Marshal(actualMap)
assert.NoError(t, err)

expected, err := json.Marshal(map[string]interface{}{
"bar": "World",
"foo": "Hello",
t.Run("should match the original json marshal", func(t *testing.T) {
expected, err := json.Marshal(v)
assert.NoError(t, err)

assert.JSONEq(t, string(expected), string(actual))
})
assert.NoError(t, err)

assert.Equal(t, string(expected), string(actual))
t.Run("should match the expected map", func(t *testing.T) {
expectedMap, err := json.Marshal(map[string]interface{}{
"bar": "World",
"foo": "Hello",
"embedded": map[string]interface{}{
"qux": "Big",
},
})
assert.NoError(t, err)
assert.JSONEq(t, string(expectedMap), string(actual))
})
}

type TestMarshal_EmbeddedEmpty struct {
Expand Down

0 comments on commit 5579d0b

Please # to comment.