diff --git a/viper.go b/viper.go index 4a5b1eb..389a58e 100644 --- a/viper.go +++ b/viper.go @@ -526,13 +526,14 @@ func (v *Viper) Get(key string) interface{} { // Returns new Viper instance representing a sub tree of this instance func Sub(key string) *Viper { return v.Sub(key) } func (v *Viper) Sub(key string) *Viper { - data, ok := v.Get(key).(map[string]interface{}) - if !ok { + subv := New() + data := v.Get(key) + if reflect.TypeOf(data).Kind() == reflect.Map { + subv.config = cast.ToStringMap(data) + return subv + } else { return nil } - subv := New() - subv.config = data - return subv } // Returns the value associated with the key as a string diff --git a/viper_test.go b/viper_test.go index e9bb3f4..fcb9c4e 100644 --- a/viper_test.go +++ b/viper_test.go @@ -730,7 +730,10 @@ func TestSub(t *testing.T) { v.SetConfigType("yaml") v.ReadConfig(bytes.NewBuffer(yamlExample)) - subv := v.Sub("clothing.pants") + subv := v.Sub("clothing") + assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("pants.size")) + + subv = v.Sub("clothing.pants") assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("size")) subv = v.Sub("clothing.pants.size")