I'm trying to access a nested field like the services
key for example from a yaml file I unmarshalled. For what it's worth I don't want to have to build a struct
that reflects the structure of the yaml file since it may not always take this form. The yaml file looks like the following:
declared-services:
Cloudant:
label: cloudantNoSQLDB
plan: Lite
applications:
- name: myProject
memory: 512M
instances: 1
random-route: true
buildpack: java
services:
- Cloudant
timeout: 180
env:
services_autoconfig_excludes: cloudantNoSQLDB=config
The code looks like this
import "gopkg.in/yaml.v2"
func getManifestConfig() *Manifest {
wd, _ := os.Getwd()
manPath := wd + "/JavaProject/" + manifest
var man map[string]interface{}
f, err := ioutil.ReadFile(manPath)
if err != nil {
e(err) //irrelevant method that prints error messages
}
yaml.Unmarshal(f, &man)
fmt.Println(man["applications"]) //This will print all the contents under applications
fmt.Println(man["applications"].(map[string]interface{})["services"]) //panic: interface conversion: interface {} is []interface {}, not map[string]interface {}
return nil
}
I think your intent is to use a mapping for applications
. If so, delete the "-" following the text "applications:":
declared-services:
Cloudant:
label: cloudantNoSQLDB
plan: Lite
applications:
name: myProject
memory: 512M
instances: 1
random-route: true
buildpack: java
services:
- Cloudant
timeout: 180
env:
services_autoconfig_excludes: cloudantNoSQLDB=config
Access the applications
field as a map[interface{}]interface{}
:
fmt.Println(man["applications"].(map[interface{}]interface{})["services"])
A good way to debug issues like this is to print the value with "%#v":
fmt.Printf("%#v
", man["applications"])
// output with the "-"
// []interface {}{map[interface {}]interface {}{"buildpack":"java", "services":[]interface {}{"Cloudant"}, "timeout":180, "name":"myProject", "memory":"512M", "instances":1, "random-route":true}}
// output without the "-":
// map[interface {}]interface {}{"instances":1, "random-route":true, "buildpack":"java", "services":[]interface {}{"Cloudant"}, "timeout":180, "name":"myProject", "memory":"512M"}