Skip to content

Commit 6053eb2

Browse files
author
Chang Hua Ou
committed
more API on map & array
1 parent f8280fe commit 6053eb2

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

simpleyaml.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,21 @@ func (y *Yaml) Array() ([]interface{}, error) {
8282
return nil, errors.New("type assertion to []interface{} failed")
8383
}
8484

85+
func (y *Yaml) IsArray() bool {
86+
_, err := y.Array()
87+
88+
return err == nil
89+
}
90+
91+
// return the size of array
92+
func (y *Yaml)GetArraySize() (int, error ) {
93+
a, err := y.Array()
94+
if err != nil {
95+
return 0, err
96+
}
97+
return len( a ), nil
98+
}
99+
85100
// GetIndex returns a pointer to a new `Yaml` object.
86101
// for `index` in its `array` representation
87102
//
@@ -135,3 +150,25 @@ func (y *Yaml) Map() (map[interface{}]interface{}, error) {
135150
}
136151
return nil, errors.New("type assertion to map[interface]interface{} failed")
137152
}
153+
154+
// Check if it is a map
155+
func (y *Yaml)IsMap() bool {
156+
_, err := y.Map()
157+
return err == nil
158+
}
159+
160+
// Get all the keys of the map
161+
func (y *Yaml)GetMapKeys() ([]string,error) {
162+
m, err := y.Map()
163+
164+
if err != nil {
165+
return nil, err
166+
}
167+
keys := make([]string, 0 )
168+
for k, _ := range m {
169+
if s,ok := k.(string) ; ok {
170+
keys = append( keys, s )
171+
}
172+
}
173+
return keys, nil
174+
}

simpleyaml_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,22 @@ func TestArray(t *testing.T) {
138138
t.Fatal("emails length not equal 2")
139139
}
140140
}
141+
142+
143+
func TestMap(t *testing.T) {
144+
y, err := NewYaml( data )
145+
if err != nil {
146+
t.Fatal("init yaml failed")
147+
}
148+
if !y.IsMap() {
149+
t.Fatal( "map check failed")
150+
}
151+
152+
keys, err := y.GetMapKeys()
153+
if err != nil {
154+
t.Fatal( "get keys from map is failed" )
155+
}
156+
if len( keys ) != 6 {
157+
t.Fatal( "fail to check number of keys")
158+
}
159+
}

0 commit comments

Comments
 (0)