我正在尝试使用一个对象数组来解析yaml文件,该对象数组根据其type
字段可以具有不同的结构。例如
conditions:
- type: branch
value:
str: master
- type: boolean
value: true
我已经阅读了数十个stackoverflow问题和各种博客文章,但这远不止于此:
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("\n")
}
}
布尔类型断言有效,但condition
结构或map[string][string]
的分支类型无效。我如何获得分支的价值?如何处理更大,更复杂的Yaml文件?
注意:在我的情况下,每种类型的结构都是已知的,我不必处理任何用户定义的动态结构