无法在 go 中循环遍历 yaml.MapItem.Value
Cannot loop through yaml.MapItem.Value in go
我正在尝试解析 yaml 文件,同时保持正在处理的表的顺序(由于外键问题)。
fixtures.yaml
table1:
-id: 1
field1: "some value"
field2: "some value"
table2:
-id: 1
field1: "some value"
field2: "some value"
...some more data...
main.go
yamlContent, err := ioutil.ReadFile("fixtures.yaml")
yamlOutput := yaml.MapSlice{}
err := yaml.Unmarshal(yamlContent, &yamlOutput)
if err != nil {
log.Fatal(err)
}
for _, tableData := range yamlOutput {
//Table Name
fmt.Println(tableData.Key)
//Table Data
fmt.Println(tableData.Value)
// Error here
for _, row := range tableData.Value {
fmt.Println(row)
}
}
tableData.Value 的值看起来像这样:
[[{id 1} {field1 some value} {field2 some value} {field3 some value} {field4 some value} {field5 some value}]]
问题是我无法通过 tableData.Value
。每当我这样做时,我都会收到错误消息:
cannot range over tableData.Value (type interface {})
但是每当我使用 reflect.TypeOf(tableData.Value)
时,我都会得到 []interface {}
我应该怎么做才能遍历每一行然后遍历每个键值对?我是 Go 的新手,所以我不太确定下一步该做什么。
如果您有一个 static 类型 interface{}
的值,其 dynamic 类型是 []interface{}
那么您必须 type-assert 将其设置为动态类型才能覆盖切片。
if v, ok := tableData.Value.([]interface{}); ok {
for _, row := range v {
fmt.Println(row)
}
}
我正在尝试解析 yaml 文件,同时保持正在处理的表的顺序(由于外键问题)。
fixtures.yaml
table1:
-id: 1
field1: "some value"
field2: "some value"
table2:
-id: 1
field1: "some value"
field2: "some value"
...some more data...
main.go
yamlContent, err := ioutil.ReadFile("fixtures.yaml")
yamlOutput := yaml.MapSlice{}
err := yaml.Unmarshal(yamlContent, &yamlOutput)
if err != nil {
log.Fatal(err)
}
for _, tableData := range yamlOutput {
//Table Name
fmt.Println(tableData.Key)
//Table Data
fmt.Println(tableData.Value)
// Error here
for _, row := range tableData.Value {
fmt.Println(row)
}
}
tableData.Value 的值看起来像这样:
[[{id 1} {field1 some value} {field2 some value} {field3 some value} {field4 some value} {field5 some value}]]
问题是我无法通过 tableData.Value
。每当我这样做时,我都会收到错误消息:
cannot range over tableData.Value (type interface {})
但是每当我使用 reflect.TypeOf(tableData.Value)
时,我都会得到 []interface {}
我应该怎么做才能遍历每一行然后遍历每个键值对?我是 Go 的新手,所以我不太确定下一步该做什么。
如果您有一个 static 类型 interface{}
的值,其 dynamic 类型是 []interface{}
那么您必须 type-assert 将其设置为动态类型才能覆盖切片。
if v, ok := tableData.Value.([]interface{}); ok {
for _, row := range v {
fmt.Println(row)
}
}