Skip to content

Commit

Permalink
Fix ToMap for tables in mixed-type arrays (#453)
Browse files Browse the repository at this point in the history
  • Loading branch information
mstetson authored Nov 15, 2020
1 parent 5b4e7e5 commit 1bd9461
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
21 changes: 20 additions & 1 deletion tomltree_write.go
Original file line number Diff line number Diff line change
Expand Up @@ -510,8 +510,27 @@ func (t *Tree) ToMap() map[string]interface{} {
case *Tree:
result[k] = node.ToMap()
case *tomlValue:
result[k] = node.value
result[k] = node.toValue()
}
}
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:
return v
}
}
15 changes: 15 additions & 0 deletions tomltree_write_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,21 @@ func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) {
testMaps(t, treeMap, expected)
}

func TestTreeWriteToMapWithTableInMixedArray(t *testing.T) {
tree, _ := Load(`a = ["foo", {bar = "baz"}]`)
expected := map[string]interface{}{
"a": []interface{}{
"foo",
map[string]interface{}{
"bar": "baz",
},
},
}
treeMap := tree.ToMap()

testMaps(t, treeMap, expected)
}

func TestTreeWriteToFloat(t *testing.T) {
tree, err := Load(`a = 3.0`)
if err != nil {
Expand Down

0 comments on commit 1bd9461

Please sign in to comment.