Fix ToMap for tables in nested mixed-type arrays (#461)

Co-authored-by: Micah Stetson <micah@schoolsplp.com>
This commit is contained in:
Thomas Pelletier
2021-01-06 20:34:25 -05:00
committed by GitHub
parent 2e01f733df
commit ba1b12be14
2 changed files with 39 additions and 19 deletions
+14 -15
View File
@@ -510,27 +510,26 @@ 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
func tomlValueToGo(v interface{}) interface{} {
if tree, ok := v.(*Tree); ok {
return tree.ToMap()
}
}
return s
default:
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
}
+23 -2
View File
@@ -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",
[]interface{}{
"bar",
map[string]interface{}{
"bar": "baz",
"baz": "quux",
},
},
[]interface{}{
map[string]interface{}{
"a": "b",
},
map[string]interface{}{
"c": "d",
},
},
},
}