亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 golang 中解析 yaml 時出錯

在 golang 中解析 yaml 時出錯

Go
躍然一笑 2023-03-21 15:19:28
我有一個像下面這樣的 yaml,我需要使用 go 來解析它。當我嘗試使用解析運行代碼時出現錯誤。下面是代碼:var runContent= []byte(`- runners:   - name: function1     type: func1      - command: spawn child process      - command: build      - command: gulp  - name: function1    type: func2      - command: run function 1  - name: function3    type: func3      - command: ruby build  - name: function4    type: func4      - command: go build `)這些是類型:type Runners struct {    runners string `yaml:"runners"`        name string `yaml:”name”`        Type: string  `yaml: ”type”`        command  [] Command }type Command struct {    command string `yaml: ”command”`}runners := Runners{}err = yaml.Unmarshal(runContent, &runners)if err != nil {    log.Fatalf("Error : %v", err)}當我嘗試解析它時出現錯誤invalid map,這里可能遺漏了什么?
查看完整描述

1 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

您發布的代碼包含多個錯誤,包括 struct field Type。您的代碼中提供的 yaml 無效。這將導致在將 yaml 解組為結構時出錯。

在 go 中解組 yaml 時,要求:

解碼值的類型應與輸出中的相應值兼容。如果一個或多個值由于類型不匹配而無法解碼,解碼將繼續部分進行,直到 YAML 內容結束,并返回一個 *yaml.TypeError,其中包含所有缺失值的詳細信息。

與此同時:

結構字段只有在導出時才會被解組(首字母大寫),并且使用小寫的字段名稱作為默認鍵進行解組。

定義標簽時也有錯誤yaml,其中包含空格。自定義鍵可以通過字段標簽中的“yaml”名稱來定義:第一個逗號之前的內容用作鍵。

type Runners struct {


    runners string `yaml:"runners"` // fields should be exportable

        name string `yaml:”name”`

        Type: string  `yaml: ”type”` // tags name should not have space in them.

        command  [] Command 

要使結構可導出,請將結構和字段轉換為大寫首字母并刪除 yaml 標簽名稱中的空格:


type Runners struct {

    Runners string `yaml:"runners"`

    Name string `yaml:"name"`

    Type string `yaml:"type"`

    Command  []Command 

}


type Command struct {

    Command string `yaml:"command"`

}

修改下面的代碼以使其工作。


package main


import (

    "fmt"

    "log"


    "gopkg.in/yaml.v2"

)


var runContent = []byte(`

- runners:

  - name: function1

    type:

    - command: spawn child process

    - command: build

    - command: gulp

  - name: function1

    type:

    - command: run function 1

  - name: function3

    type:

    - command: ruby build

  - name: function4

    type:

    - command: go build

`)


type Runners []struct {

    Runners []struct {

        Type []struct {

            Command string `yaml:"command"`

        } `yaml:"type"`

        Name string `yaml:"name"`

    } `yaml:"runners"`

}


func main() {


    runners := Runners{}

    // parse mta yaml

    err := yaml.Unmarshal(runContent, &runners)

    if err != nil {

        log.Fatalf("Error : %v", err)

    }

    fmt.Println(runners)

}

游樂場示例

在此處在線驗證您的 yaml https://codebeautify.org/yaml-validator/cb92c85b


查看完整回答
反對 回復 2023-03-21
  • 1 回答
  • 0 關注
  • 207 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號