我从开始开始,官方documentation似乎更适合那些已经知道Go并且只想查看内容的人。我希望在这里向正确的方向稍微推动一下。
我要做的事情:使用 BurntSushi&#39> TOML解析器解析TOML
个配置文件,该解析器包含多个元素共享相同的基本特征。
我被困的地方:我希望每件商品的相应部件都与商品一起列出。到目前为止,我只能通过其索引获得其中一个。我正在寻找的是如何以列出相应索引的所有子部分而不仅仅是特定索引的方式进行设置。我可以使用[:]
获取JSON列表,但似乎无法使其适应正常输出。
最初我考虑了[[item.part.001]]
等等,因为它在在线JSON解析器中看起来是正确的,但是无法弄清楚如何正确地将其读入Go。无论如何我都被卡住了,我对这两种类型都开放,无论哪种方式最好。
提前致谢。以下是文件的缩写最小工作示例。
demo.toml
# — — — — — — — — — — — — — — — — — — — — — — —
# First Item
# — — — — — — — — — — — — — — — — — — — — — — —
[[item]]
itemname = "Fragments"
itemdesc = "This one can get a bit longer."
[item.attributes]
material = "Basematname"
light = "Lightname"
transpc = "full"
displace = "height"
[[item.part]]
partname = "Shard"
partlink = "active"
[[item.part]]
partname = "Tear"
partlink = "deferred"
[[item.part]]
partname = "crater"
partlink = "disabled"
# — — — — — — — — — — — — — — — — — — — — — — —
# Second Item
# — — — — — — — — — — — — — — — — — — — — — — —
[[item]]
itemname = "Splash"
itemdesc = "This one also can get a bit longer."
[item.attributes]
material = "Other Basematname"
light = "Other Lightname"
transpc = "half"
displace = "bump"
[[item.part]]
partname = "Drops"
partlink = "active"
[[item.part]]
partname = "Wave"
partlink = "deferred"
demo.go
package main
import (
"fmt"
"github.com/BurntSushi/toml"
)
type item struct {
ItemName string
ItemDesc string
Attributes attributes
Part []part
}
type part struct {
PartName string
PartLink string
}
type attributes struct {
Material string
Light string
TransPC string
Displace string
}
type items struct {
Item []item
}
func main() {
var allitems items
if _, err := toml.DecodeFile("demo.toml", &allitems); err != nil {
fmt.Println(err)
return
}
fmt.Printf("\n")
for _, items := range allitems.Item {
fmt.Printf(" Item Name: %s \n", items.ItemName)
fmt.Printf(" Description: %s \n\n", items.ItemDesc)
fmt.Printf(" Material: %s \n", items.Attributes.Material)
fmt.Printf(" Lightmap: %s \n", items.Attributes.Light)
fmt.Printf(" TL Precision: %s \n", items.Attributes.TransPC)
fmt.Printf(" DP Channel: %s \n", items.Attributes.Displace)
fmt.Printf(" Part Name: %s \n", items.Part[0].PartName)
fmt.Printf(" Part Link: %s \n", items.Part[0].PartLink)
# ^
# That's where [:] won't do it.
fmt.Printf("\n────────────────────────────────────────────────────┤\n\n")
}
fmt.Printf("\n")
}
答案 0 :(得分:0)
正如评论中所指出的,您需要一个嵌套循环。而不是:
fmt.Printf(" Part Name: %s \n", items.Part[0].PartName)
fmt.Printf(" Part Link: %s \n", items.Part[0].PartLink)
使用它:
for _, part := range items.Part {
fmt.Printf(" Part Name: %s \n", part.PartName)
fmt.Printf(" Part Link: %s \n", part.PartLink)
}