pupil
pupil

Reputation: 23

How to iterate over all the YAML values in Golang?

I am trying to understand nested maps in Golang. I have a map like below, how do I iterate over all the keys?

Data:
  - name: "foo"
    bar1: 0
      k1: val1
      k2:
         val2
         val3
    bar2: 1
      k3: val4
      k4: val5
      k3: val4
      k4: val5

Upvotes: 0

Views: 4316

Answers (1)

Nipun Talukdar
Nipun Talukdar

Reputation: 5387

You have to unmarshal the data into a map (map[interface{}]interface{} or map[string]interface{}) and then you have to check the type of the values for the keys. You may use the yaml.v2 package and there might be cleaner interfaces which helps to detect the type of the values. Otherwise check the example that iterates over the keys and print the values:

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
    "reflect"
    "strings"
)

var data = `
Data:
    - name: "foo"
      bar1: 0
      k1: val1
      k2:
         val2
         val3
      bar2: 1
      k3: val4
      k4: val5
      k5: val5
      k6: val6
`

func printVal(v interface{}, depth int) {
    typ := reflect.TypeOf(v).Kind()
    if typ == reflect.Int || typ == reflect.String {
        fmt.Printf("%s%v\n", strings.Repeat(" ", depth), v)
    } else if typ == reflect.Slice {
        fmt.Printf("\n")
        printSlice(v.([]interface{}), depth+1)
    } else if typ == reflect.Map {
        fmt.Printf("\n")
        printMap(v.(map[interface{}]interface{}), depth+1)
    }

}

func printMap(m map[interface{}]interface{}, depth int) {
    for k, v := range m {
        fmt.Printf("%sKey:%s", strings.Repeat(" ", depth), k.(string))
        printVal(v, depth+1)
    }
}

func printSlice(slc []interface{}, depth int) {
    for _, v := range slc {
        printVal(v, depth+1)
    }
}

func main() {
    m := make(map[string]interface{})

    err := yaml.Unmarshal([]byte(data), &m)
    if err != nil {
        panic(err)
    }
    for k, v := range m {
        fmt.Printf("Key:%s ", k)
        printVal(v, 1)
    }
}

Upvotes: 4

Related Questions