2017-02-24 25 views
0

我試圖從解組的yaml文件中訪問嵌入字段,例如services鍵。我不想建立反映yaml文件結構的struct,因爲它可能並不總是採用這種形式。 YAML的文件如下所示:如何以通用方式引用嵌套地圖

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 

的代碼看起來像這樣

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 
} 

回答

1

我覺得你的意圖是使用映射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 

訪問applications字段作爲map[interface{}]interface{}

fmt.Println(man["applications"].(map[interface{}]interface{})["services"]) 

的一個好方法來調試問題,像這樣的打印值與「%#v」:

fmt.Printf("%#v\n", 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"} 
+0

我得到一個'恐慌:接口轉換:接口{}是[]接口{},而不是地圖[接口}}接口{}運行時錯誤@Cerise利蒙 – sreya

+0

@sreya請參閱更新d回答 –

+0

thx修復了它,你將如何解決我在評論中引用的恐慌。有沒有好的方法? – sreya