【问题标题】:Parsing YAML and return with line number解析 YAML 并返回行号
【发布时间】:2021-06-06 01:30:35
【问题描述】:

我正在从 Go 中的 YAML 输入创建一个文档生成器。它需要指定每个项目/节点是从 YAML 文件的哪一行生成的。有没有办法在 Go 中实现它?

例如这里是一个 YAML 文件

- key1: item 1
  key2: item 2
- key1: another item 1
  key2: another item 2

我想看看以下内容

[
     {'__line__': 1, 'key1': 'item 1', 'key2': 'item 2'},
     {'__line__': 3, 'key1': 'another item 1', 'key2': 'another item 2'},
]

我看到 Python Parsing YAML, return with line number 的类似问题得到了回答,但我不知道如何使用 https://pkg.go.dev/gopkg.in/yaml.v3

【问题讨论】:

    标签: parsing go yaml


    【解决方案1】:

    在 Go 中,这可以通过实现自定义 Unmarshaler 并手动设置行号来实现。

    所以让我们为文件构建我们需要的数据结构:

    type ListItem struct {
        Line int
    
        ListItemData
    }
    
    type ListItemData struct {
        Key1 string `yaml:"key1"`
        Key2 string `yaml:"key2"`
    }
    

    现在我们通过在 ListItem 类型上创建一个方法来实现 Unmarshaler 接口:

    func (li *ListItem) UnmarshalYAML(value *yaml.Node) error {
        err := value.Decode(&li.ListItemData)
        if err != nil {
            return err
        }
         
        // Save the line number
        li.Line = value.Line
    
        return nil
    }
    

    您会注意到我创建了一个内部结构,并且只将数据解码为该结构。这是因为如果我们在 li 本身上调用 Decode,我们会遇到堆栈溢出,因为解码会重复调用 UnmarshalYAML 方法。

    你可以试试这个online,看看行号设置是否正确。

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多