Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,31 @@ func (v *Viper) Sub(key string) *Viper {
return nil
}

// SubSlice returns a slice of new Viper instances representing a sub tree of this instance.
// Sub is case-insensitive for a key.
func SubSlice(key string) []*Viper { return v.SubSlice(key) }

// SubSlice returns a slice of new Viper instances representing a sub tree of this instance.
// Sub is case-insensitive for a key.
func (v *Viper) SubSlice(key string) []*Viper {
data := v.Get(key)
if data == nil {
return nil
}

if reflect.TypeOf(data).Kind() == reflect.Slice {
var vList []*Viper
for _, item := range data.([]interface{}) {
subv := New()
subv.config = cast.ToStringMap(item)
vList = append(vList, subv)
}
return vList
}

return nil
}

// GetString returns the value associated with the key as a string.
func GetString(key string) string { return v.GetString(key) }

Expand Down
24 changes: 24 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1746,6 +1746,30 @@ func TestSub(t *testing.T) {
assert.Equal(t, []string{"clothing", "pants"}, subv.parents)
}

func TestSubSlice(t *testing.T) {
yamlList := []byte(`map:
foo: bar
list:
- foo: 0
bar: 0
- foo: 1
bar: 1
`)

v := New()
v.SetConfigType("yaml")
v.ReadConfig(bytes.NewBuffer(yamlList))

subvSlice := v.SubSlice("list")
for idx, subv := range subvSlice {
assert.Equal(t, subv.GetInt("foo"), idx)
assert.Equal(t, subv.GetInt("bar"), idx)
}

subvSlice = v.SubSlice("map")
assert.Equal(t, []*Viper(nil), subvSlice)
}

func TestSubWithKeyDelimiter(t *testing.T) {
v := NewWithOptions(KeyDelimiter("::"))
v.SetConfigType("yaml")
Expand Down
Loading