如何以通用方式引用嵌套映射

时间:2017-02-24 23:55:59

标签: go yaml

我尝试访问像services键这样的嵌套字段,例如从我解组的yaml文件中访问。对于它的价值,我不想构建一个反映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 个答案:

答案 0 :(得分:0)

我认为您的意图是使用applications的映射。如果是这样,请删除文本“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"}
相关问题