这篇文章主要为大家展示了“go语言如何实现yaml转map、map遍历”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“go语言如何实现yaml转map、map遍历”这篇文章吧。
yaml文件内容
apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: mysql-snapshot spec: privileged: false allowPrivilegeEscalation: false volumes: - "*" hostNetwork: false hostIPC: false hostPID: false runAsUser: rule: RunAsAny seLinux: rule: RunAsAny supplementalGroups: rule: RunAsAny fsGroup: rule: RunAsAny
示例代码:实现了base64 编解码、yaml转map、以及map遍历
func main() { f, err := os.Open("cmd/test.yaml") if err != nil { log.Fatalln(err) return } input, _ := ioutil.ReadAll(f) // base64 编码 encodeString := base64.StdEncoding.EncodeToString(input) fmt.Println(encodeString) // base64 解码 decodeBytes, err := base64.StdEncoding.DecodeString(encodeString) if err != nil { log.Fatalln(err) } //yaml文件内容转换成map[interface{}]interface{}) resultMap := make(map[interface{}]interface{}) if err := yaml.Unmarshal(decodeBytes, &resultMap); err != nil { // error handling log.Fatalln(err) } // 遍历map ,此处取metadata.name值 for key, value := range resultMap { switch key := key.(type) { case string: if key == "metadata" { switch value := value.(type) { case string: case map[interface{}]interface{}: for k, v := range value { switch k.(type) { case string: if k == "name" { fmt.Println("value=", v) } } } } } } } }
结果
encodeString = "YXBpVmVyc2lvbjogcG9saWN5L3YxYmV0YTEKa2luZDogUG9kU2VjdXJpdHlQb2xpY3kKbWV0YWRhdGE6CiAgbmFtZTogbXlzcWwtc25hcHNob3QKc3BlYzogCiAgcHJpdmlsZWdlZDogZmFsc2UKICBhbGxvd1ByaXZpbGVnZUVzY2FsYXRpb246IGZhbHNlCiAgdm9sdW1lczoKICAtICIqIgogIGhvc3ROZXR3b3JrOiBmYWxzZQogIGhvc3RJUEM6IGZhbHNlCiAgaG9zdFBJRDogZmFsc2UKICBydW5Bc1VzZXI6CiAgICBydWxlOiBSdW5Bc0FueQogIHNlTGludXg6CiAgICBydWxlOiBSdW5Bc0FueQogIHN1cHBsZW1lbnRhbEdyb3VwczoKICAgIHJ1bGU6IFJ1bkFzQW55CiAgZnNHcm91cDoKICAgIHJ1bGU6IFJ1bkFzQW55Cg=="
value=mysql-snapshot
以上是“go语言如何实现yaml转map、map遍历”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。