go语言yaml转map、map遍历的实现
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
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) } } } } } } } }
标签: