Go 如何以常规方式引用嵌套贴图
我试图访问一个嵌套字段,例如从我解封的yaml文件中访问Go 如何以常规方式引用嵌套贴图,go,yaml,Go,Yaml,我试图访问一个嵌套字段,例如从我解封的yaml文件中访问services键。无论如何,我不想构建一个反映yaml文件结构的struct,因为它可能并不总是采用这种形式。yaml文件如下所示: declared-services: Cloudant: label: cloudantNoSQLDB plan: Lite applications: - name: myProject memory: 512M instances: 1 random-
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
代码如下所示
我认为您的目的是为
应用程序使用映射。如果是,请删除“应用程序:”后的“-”:
以映射[接口{}]接口{}
的形式访问应用程序
字段:
fmt.Println(man["applications"].(map[interface{}]interface{})["services"])
调试此类问题的一个好方法是使用“%#v”打印值:
我得到了一个panic:interface conversion:interface{}是[]interface{},而不是map[interface{}]interface{}
runtime error@Cerise Limónthx修复了它,你如何修复我在评论中引用的panic。有什么好办法吗?使用fmt.Println(man[“applications”]。([]接口{})[0]。(map[interface{}]接口{})[“services”])
避免使用问题中显示的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
fmt.Println(man["applications"].(map[interface{}]interface{})["services"])
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"}