go - 如何以通用方式引用嵌套 map

标签 go yaml

我正在尝试从我解码的 yaml 文件访问嵌套字段,例如 services 键。对于它的值(value),我不想构建一个反射(reflect) 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
}

最佳答案

我认为您的意图是为应用程序 使用映射。如果是这样,请删除文本“应用程序:”后面的“-”:

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

作为 map[interface{}]interface{} 访问 applications 字段:

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"}

关于go - 如何以通用方式引用嵌套 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42450240/

相关文章:

google-app-engine - 错误 : (gcloud. preview.app)无效的选择: 'run'

go - 使用反射,如何动态创建结构 "type"?

go - 为什么解码此 API 响应会返回意外的 EOF?

azure - 如何将测试失败屏幕截图附加到 YAML 中的 Azure Pipeline 测试运行?

amazon-web-services - 如何在本地使用 SAM 以及部署时重用 AWS 上的层?

go - 为什么这个将字符串转换为整数的 Golang 代码失败了?

go - 如何处理客户端超时错误?

azure - 有没有办法以编程方式将 YAML 文件存储在 Azure Key Vault 中?

spring - 如何使用gradle任务将.yml转换为.properties?

javascript - Gatsby - 在解析/显示 YAML 文件内容时是否可以保留换行符?