示例 yaml 文件:final-result.yml- category: 1 rules: - name: a results: - asset: b advice: c- category: 2 rules: - name: d results: - asset: e advice: f我嘗試打包以取消元帥:gopkg.in/yaml.v2package mainimport ( "io/ioutil" "log" "gopkg.in/yaml.v2")type FinalResult struct { category string `yaml:"category"` rules []RulesItem `yaml:"rules,flow"`}type RulesItem struct { name string `yaml:"name"` results []ResultsItem `yaml:"results,flow"`}type ResultsItem struct { asset string `yaml:"asset"` advice string `yaml:"advice"`}func main() { var result []FinalResult content, err := ioutil.ReadFile("final-result.yml") if err != nil { log.Fatal(err.Error()) return } err = yaml.Unmarshal(content, &result) if err != nil { log.Fatal("Failed to parse file ", err) } log.Println(result)}但它給出了一個(gè)空的結(jié)果:[{ []} { []}]
1 回答

人到中年有點(diǎn)甜
TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
根據(jù)文檔,您應(yīng)該公開(kāi)結(jié)構(gòu)字段,以便 unmarshal 正確填充數(shù)據(jù):
僅當(dāng)導(dǎo)出結(jié)構(gòu)字段時(shí),結(jié)構(gòu)字段才會(huì)取消編組(首字母為大寫)
更改類型定義后,您的代碼將按預(yù)期方式工作,如下所示:
type FinalResult struct {
Category string `yaml:"category"`
Rules []RulesItem `yaml:"rules,flow"`
}
type RulesItem struct {
Name string `yaml:"name"`
Results []ResultsItem `yaml:"results,flow"`
}
type ResultsItem struct {
Asset string `yaml:"asset"`
Advice string `yaml:"advice"`
}
- 1 回答
- 0 關(guān)注
- 112 瀏覽
添加回答
舉報(bào)
0/150
提交
取消