使用golang从YAML解码/编码多行字符串字段

时间:2018-11-28 23:54:28

标签: go yaml

YAML文件可以包含带有“多行字符串”数据的字段。下面的示例:

Data:
  Foo: |
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten

如何在Golang中正确地对它们进行编码和解码?Data字段的类型map[string][]byte应该是什么?

我尝试过:

import (
    yamlv2 "gopkg.in/yaml.v2"
)

type data struct {
  Data map[string][]byte
}

func decode(bytes []byte) (*data, error) {
  d := &data{}

  err := yamlv2.Unmarshal(bytes, d)
  if err != nil {
    return nil, err
  }
  return d, nil
}

另请参见Playground

1 个答案:

答案 0 :(得分:1)

您将以与普通字符串相同的方式解析多行字符串:

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
    "log"
)

var yamlString = `
Data:
  Foo: |
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten`

type data struct {
    Data map[string]string `yaml:"Data"`
}

func main() {
    t := data{}

    err := yaml.Unmarshal([]byte(yamlString), &t)
    if err != nil {
        log.Fatalf("error: %v", err)
    }

    if foo, ok := t.Data["Foo"]; ok {
        fmt.Printf("--- t:\n%v\n\n", foo)
    }
}