Home >Backend Development >Golang >go Lang load cannot process yaml file

go Lang load cannot process yaml file

王林
王林forward
2024-02-09 16:30:191332browse

go Lang load无法处理yaml文件

php editor Zimo found that many Go language developers encountered problems when processing yaml files. Although the Go language provides the load function for loading yaml files, this function cannot correctly handle the parsing of yaml files. This problem has caused many developers to encounter difficulties when processing YAML files. So, how to solve this problem? In this article, we will introduce some solutions to help developers handle YAML files smoothly.

Question content

I am trying to read a yaml file and store it in a variable, but for some reason the array object in the yaml file cannot unmarshal the file. It shows blank data.

The following is the content of my yaml file

---
version: "1.2"

bunits:
  - name: buname
    bugroupid: asd
    bustgroupid: asd
  - name: buname2
    bugroupid: asd2
    bustgroupid: asd2

The following is the code being used

type SResponse struct {
   Version       string         `json:"version"`
   BUnits []BUnit `json:"bUnits"`
}

type BUnit struct {
    Name                      string `json:"name"`
    BuUnitGroupID       string `json:"buGroupID"`
    BuUnitStGroupID string `json:"buStaticGroupID"`
}
func main() {

    _printf := fmt.Printf
    _printf("Start")
    var sListResponse SResponse

    source, err2 := ioutil.ReadFile("squads2.yml")

    if err2 != nil {
        _printf("Couldn't read yaml file.")
}

    err2 = yaml.Unmarshal(source, &sListResponse)
    if err2 != nil {
    _printf("Error")
    }

    _printf("Output: %s\n", sListResponse)
}

The code reads the version part, but the bunits array is empty. Please make suggestions.

Workaround

Decorate your struct with json tag - you may or may not need to (depending on whether you later export/import in json format this data). But your problem at hand is the yaml import - so you need to decorate your struct definition with the yaml tag.

To support json and yaml marshalling/unmarshaling, simply update your tags as follows:

type SResponse struct {
    Version string  `json:"version" yaml:"version"`
    BUnits  []BUnit `json:"bUnits" yaml:"bUnits"`
}

type BUnit struct {
    Name            string `json:"name" yaml:"name"`
    BuUnitGroupID   string `json:"buGroupID" yaml:"buGroupID"`
    BuUnitStGroupID string `json:"buStaticGroupID" yaml:"buStaticGroupID"`
}

Or if you don't need json encoding/decoding, just remove the json tag.

The above is the detailed content of go Lang load cannot process yaml file. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete