Skip to content

Commit 7deb230

Browse files
committed
for empty slices no header is exported
1 parent efaf9c9 commit 7deb230

File tree

2 files changed

+38
-18
lines changed

2 files changed

+38
-18
lines changed

flatstruct.go

+21-18
Original file line numberDiff line numberDiff line change
@@ -58,27 +58,30 @@ func CompNRowsCols(s interface{}) (nrows, ncols int) {
5858

5959
// FlattenSlice TODO
6060
func FlattenSlice(headerBase string, s interface{}) (headers []string, rows [][]string, err error) {
61-
headers = append(headers, headerBase)
62-
6361
sValue := reflect.ValueOf(s)
64-
var newHeaders []string
65-
for i := 0; i < sValue.Len(); i++ {
66-
var newRows [][]string
67-
var err error
68-
newHeaders, newRows, err = FlattenBegin(headerBase, sValue.Index(i).Interface())
69-
if err != nil {
70-
// TODO
71-
}
72-
iJSON, err := json.Marshal(i)
73-
if err != nil {
74-
// TODO
75-
}
76-
for r := 0; r < len(newRows); r++ {
77-
newRows[r] = append([]string{string(iJSON)}, newRows[r]...)
62+
63+
if sValue.Len() > 0 {
64+
headers = append(headers, headerBase)
65+
var newHeaders []string
66+
for i := 0; i < sValue.Len(); i++ {
67+
var newRows [][]string
68+
var err error
69+
newHeaders, newRows, err = FlattenBegin(headerBase, sValue.Index(i).Interface())
70+
if err != nil {
71+
// TODO
72+
}
73+
iJSON, err := json.Marshal(i)
74+
if err != nil {
75+
// TODO
76+
}
77+
for r := 0; r < len(newRows); r++ {
78+
newRows[r] = append([]string{string(iJSON)}, newRows[r]...)
79+
}
80+
rows = append(rows, newRows...)
7881
}
79-
rows = append(rows, newRows...)
82+
headers = append(headers, newHeaders...)
8083
}
81-
headers = append(headers, newHeaders...)
84+
8285
return headers, rows, nil
8386
}
8487

flatstruct_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,23 @@ func TestFlatStruct(t *testing.T) {
8787
flatUnflatTest(t, structured, flattened, headerBase, "Flatten flat stuct value", "Should be flattened flat struct value", "Flatten flat stuct value", "Should be unflattened flat struct value")
8888
}
8989

90+
func TestStructWithEmptySlice(t *testing.T) {
91+
type WithEmptySlice struct {
92+
A string `json:"a"`
93+
EmptySlice []int `json:"empty_slice"`
94+
}
95+
structured := WithEmptySlice{
96+
A: "aval",
97+
EmptySlice: nil,
98+
}
99+
flattened := [][]string{
100+
{"myBase.a"},
101+
{`"aval"`},
102+
}
103+
headerBase := "myBase"
104+
flatUnflatTest(t, structured, flattened, headerBase, "Flatten stuct value with emtpy slice", "Should be flattened struct value with emtpy slice", "Flatten stuct value with emtpy slice", "Should be unflattened struct value with emtpy slice")
105+
}
106+
90107
func TestNestedStruct(t *testing.T) {
91108
type ABCD struct {
92109
AB AB `json:"ab"`

0 commit comments

Comments
 (0)