Skip to content

Commit

Permalink
Fix #5: skip unexported fields, allow nil values
Browse files Browse the repository at this point in the history
Thanks @RangelReale for bringing that issue up and proposing a fix!
  • Loading branch information
mweibel committed Nov 6, 2017
1 parent 73de227 commit ca7f52a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions sheriff.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ func Marshal(options *Options, data interface{}) (interface{}, error) {
if jsonOpts.Contains("omitempty") && isEmptyValue(val) {
continue
}
// skip unexported fields
if !val.IsValid() || !val.CanInterface() {
continue
}

// if there is an anonymous field which is a struct
// we want the childs exposed at the toplevel to be
Expand Down Expand Up @@ -144,6 +148,10 @@ func Marshal(options *Options, data interface{}) (interface{}, error) {
//
// There is support for types implementing the Marshaller interface, arbitrary structs, slices, maps and base types.
func marshalValue(options *Options, v reflect.Value) (interface{}, error) {
// return nil on nil pointer struct fields
if !v.IsValid() || !v.CanInterface() {
return nil, nil
}
val := v.Interface()

if marshaller, ok := val.(Marshaller); ok {
Expand Down
32 changes: 32 additions & 0 deletions sheriff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -464,3 +464,35 @@ func TestMarshal_EmbeddedFieldEmpty(t *testing.T) {

assert.Equal(t, string(expected), string(actual))
}

type TestInlineStruct struct {
tableName struct{ Test string } `json:"-"`
tableNameWithTag struct{ Test string } `json:"foo"`

Field string `json:"field"`
Field2 *string `json:"field2"`
}

func TestMarshal_InlineStruct(t *testing.T) {
v := TestInlineStruct{
tableName: struct{ Test string }{"test"},
tableNameWithTag: struct{ Test string }{"testWithTag"},
Field: "World",
Field2: nil,
}
o := &Options{}

actualMap, err := Marshal(o, v)
assert.NoError(t, err)

actual, err := json.Marshal(actualMap)
assert.NoError(t, err)

expected, err := json.Marshal(map[string]interface{}{
"field": "World",
"field2": nil,
})
assert.NoError(t, err)

assert.Equal(t, string(expected), string(actual))
}

0 comments on commit ca7f52a

Please sign in to comment.