Rahul
Rahul

Reputation: 1807

Golang and yaml with dynamic schema

I have a YAML structure with dynamic schema e.g. I can have the following yaml:

array:
  - name: myvar
    val: 1
  - name: mymap
    val: [ 1, 2]

Goyaml maps yaml to Go struct, which should declare definite type. Here, val is either a signle number, or an array or even a map.

Which is the best solution for this situation?

Upvotes: 2

Views: 2239

Answers (1)

RayfenWindspear
RayfenWindspear

Reputation: 6284

I decided to add an answer showing a type assertion instead of the reflect package. You can decide which is best for your application. I personally prefer the builtin functions over the complexity of the reflect package.

var data = `
array:
  - name: myvar
    val: 1
  - name: mymap
    val: [1, 2]
`

type Data struct {
    Array []struct {
        Name string
        Val  interface{}
    }
}

func main() {
    d := Data{}
    err := yaml.Unmarshal([]byte(data), &d)
    if err != nil {
        log.Fatal(err)
    }

    for i := range d.Array {
        switch val := d.Array[i].(type) {
        case int:
            fmt.Println(val) // is integer
        case []int:
            fmt.Println(val) // is []int
        case []string:
            fmt.Println(val) // is []string
            //  .... you get the idea
        default:
            log.Fatalf("Type unaccounted for: %+v\n", d.Array[i])
        }
    }

}

Upvotes: 3

Related Questions