我正在尝试从我解码的 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/