I'm attempting to parse a yaml file with an array of objects that can have different structures depending on their type
field. e.g.
conditions:
- type: branch
value:
str: master
- type: boolean
value: true
I've read dozens of stackoverflow questions and various blog posts, but this is are far as I've gotten:
package main
import (
"log"
"gopkg.in/yaml.v2"
)
type conditions struct {
Conditions []condition
}
type condition struct {
Type string
Value interface{}
}
type stringCondition struct {
Str string
}
func main() {
c := conditions{}
text := `
conditions:
- type: branch
value:
str: master
- type: boolean
value: true
`
err := yaml.Unmarshal([]byte(text), &c)
if err != nil {
log.Fatal(err)
}
for i, b := range c.Conditions {
value := b.Value
switch b.Type {
case "branch":
log.Printf("%v is a branch condition", i)
if val, ok := value.(stringCondition); ok {
log.Printf("%v value: %v", i, val)
} else if val, ok := value.(map[string]string); ok {
log.Printf("%v value: %v", i, val)
} else {
log.Printf("type assertions failed")
log.Printf("%v value: %v", i, val)
log.Printf("value type: %T", value)
}
case "boolean":
log.Printf("%v a boolean condition", i)
if val, ok := value.(bool); ok {
log.Printf("%v value: %v", i, val)
} else {
log.Printf("type assertions failed")
}
default:
log.Fatalf("unknown type in condition: %v", c.Conditions[0].Type)
}
log.Println("
")
}
}
The boolean type assertion works, but not the branch type for either the condition
struct or a map[string][string]
. How would I get the value of the branch? How would I handle a larger and more complex yaml file?
Note: in my case, the structures for each type are all known, I don't have to handle any user-defined dynamic structures