Skip to content

Commit

Permalink
Fix ToMap for tables and table arrays in nested mixed-type arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
mstetson committed Nov 20, 2020
1 parent 1bd9461 commit 6642afc
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 19 deletions.
34 changes: 18 additions & 16 deletions tomltree_write.go
Original file line number Diff line number Diff line change
Expand Up @@ -510,27 +510,29 @@ func (t *Tree) ToMap() map[string]interface{} {
case *Tree:
result[k] = node.ToMap()
case *tomlValue:
result[k] = node.toValue()
result[k] = tomlValueToGo(node.value)
}
}
return result
}

// toValue converts a tomlValue to a built-in Go type.
func (t *tomlValue) toValue() interface{} {
switch v := t.value.(type) {
case []interface{}:
s := make([]interface{}, len(v))
for i := range s {
switch e := v[i].(type) {
case *Tree:
s[i] = e.ToMap()
default:
s[i] = e
}
}
return s
default:
func tomlValueToGo(v interface{}) interface{} {
if tv, ok := v.(*tomlValue); ok {
v = tv.value
}
if tree, ok := v.(*Tree); ok {
return tree.ToMap()
}

rv := reflect.ValueOf(v)

if rv.Kind() != reflect.Slice {
return v
}
values := make([]interface{}, rv.Len())
for i := 0; i < rv.Len(); i++ {
item := rv.Index(i).Interface()
values[i] = tomlValueToGo(item)
}
return values
}
27 changes: 24 additions & 3 deletions tomltree_write_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,12 +296,33 @@ func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) {
}

func TestTreeWriteToMapWithTableInMixedArray(t *testing.T) {
tree, _ := Load(`a = ["foo", {bar = "baz"}]`)
tree, _ := Load(`a = [
"foo",
[
"bar",
{baz = "quux"},
],
[
{a = "b"},
{c = "d"},
],
]`)
expected := map[string]interface{}{
"a": []interface{}{
"foo",
map[string]interface{}{
"bar": "baz",
[]interface{}{
"bar",
map[string]interface{}{
"baz": "quux",
},
},
[]interface{}{
map[string]interface{}{
"a": "b",
},
map[string]interface{}{
"c": "d",
},
},
},
}
Expand Down

0 comments on commit 6642afc

Please sign in to comment.