Skip to content

Commit

Permalink
Implement ToMap
Browse files Browse the repository at this point in the history
  • Loading branch information
pelletier committed Apr 19, 2016
1 parent 92a648a commit c383a9a
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
23 changes: 23 additions & 0 deletions tomltree_conversions.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,26 @@ func (t *TomlTree) ToString() string {
return t.toToml("", "")
}

// ToMap recursively generates a representation of the current tree using map[string]interface{}.
func (t *TomlTree) ToMap() map[string]interface{} {
result := map[string]interface{}{}

for k, v := range t.values {
switch node := v.(type) {
case []*TomlTree:
result[k] = make([]interface{}, 0)
for _, item := range node {
result[k] = item.ToMap()
}
case *TomlTree:
result[k] = node.ToMap()
case map[string]interface{}:
sub := TreeFromMap(node)
result[k] = sub.ToMap()
case *tomlValue:
result[k] = node.value
}
}

return result
}
60 changes: 60 additions & 0 deletions tomltree_conversions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package toml

import (
"reflect"
"testing"
"time"
)

func testMaps(t *testing.T, actual, expected map[string]interface{}) {
if !reflect.DeepEqual(actual, expected) {
t.Fatal("trees aren't equal.\n", "Expected:\n", expected, "\nActual:\n", actual)
}
}

func TestTomlTreeConversionToMapSimple(t *testing.T) {
tree, _ := Load("a = 42\nb = 17")

expected := map[string]interface{}{
"a": int64(42),
"b": int64(17),
}

testMaps(t, tree.ToMap(), expected)
}

func TestTomlTreeConversionToMapExampleFile(t *testing.T) {
tree, _ := LoadFile("example.toml")
expected := map[string]interface{}{
"title": "TOML Example",
"owner": map[string]interface{}{
"name": "Tom Preston-Werner",
"organization": "GitHub",
"bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
"dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
},
"database": map[string]interface{}{
"server": "192.168.1.1",
"ports": []interface{}{int64(8001), int64(8001), int64(8002)},
"connection_max": int64(5000),
"enabled": true,
},
"servers": map[string]interface{}{
"alpha": map[string]interface{}{
"ip": "10.0.0.1",
"dc": "eqdc10",
},
"beta": map[string]interface{}{
"ip": "10.0.0.2",
"dc": "eqdc10",
},
},
"clients": map[string]interface{}{
"data": []interface{}{
[]interface{}{"gamma", "delta"},
[]interface{}{int64(1), int64(2)},
},
},
}
testMaps(t, tree.ToMap(), expected)
}

0 comments on commit c383a9a

Please sign in to comment.