【问题标题】:How to marshal a multiline string to yaml value如何将多行字符串编组为 yaml 值
【发布时间】:2018-12-12 17:23:47
【问题描述】:

我有一个结构

type Products struct {
    Name    string
    Version string
    Description     string
}

持有一个多行字符串常量作为Description字段的值,常量如下

const DEFAULT_DESCRIPTION = `Please add the description here without removing the literal block (|)
    Sample description will be as follows,
    Fixes for the following in rabbitmq transport
    (i)   Channel not closing issue in rabbitmq publisher
    (ii)  Performance improvements to the transport by introducing a channel pool (configurable) and parameterising queue and exchange creation.
    (iii) Allow configuring connection factory by name in target url`

然后我使用包gopkg.in/yaml.v2 来编组上述结构(其中包含上述常量作为其字段的值),如下所示

data, err = yaml.Marshal(updateDescriptorV3)

并使用os.file.Write() 将生成的yaml 内容写入文件 但是在上面生成的yaml 文件中,在literal_block 符号(|)之后存在一个额外的- 我做错了什么?

  description: |-
Please add the description here without removing the literal block (|)
Sample description will be as follows,
Fixes for the following in rabbitmq transport
(i)   Channel not closing issue in rabbitmq publisher
(ii)  Performance improvements to the transport by introducing a channel pool (configurable) and parameterising queue and exchange creation.
(iii) Allow configuring connection factory by name in target url

需要做些什么才能将上述常量作为yaml中的literal_block如下?

  description: |
Please add the description here without removing the literal block (|)
Sample description will be as follows,
Fixes for the following in rabbitmq transport
(i)   Channel not closing issue in rabbitmq publisher
(ii)  Performance improvements to the transport by introducing a channel pool (configurable) and parameterising queue and exchange creation.
(iii) Allow configuring connection factory by name in target url

【问题讨论】:

  • 所以updateDescriptorV3Products 的一个实例?
  • @KasunSiyambalapitiya 检查this answer。 YAML 与简单相反。有 9 种写多行字符串的方法。从那个答案|-: "strip": remove the line feed, remove the trailing blank lines..
  • 在有人开始反对之前,还记得整个 YAML 规范吗?真的吗?它比 XML 大,不同的库使用不同的规则进行序列化。 YAML: Probably not so great after all.
  • @KasunSiyambalapitiya 对 YAML 感到惊讶是完全可以的,即使是专家也无法记住每一个神秘的组合。事实上,链接答案的作者必须至少为多行字符串There are 5 6 NINE (or 63*, depending how you count) different ways 编辑答案 3 次。答案有 35 个修订版
  • 您可能还想阅读我关于 YAML 引用的文章:blogs.perl.org/users/tinita/2018/03/…

标签: parsing go yaml multilinestring


【解决方案1】:

它工作正常。您的多行字符串不会以换行符结尾,因此 YAML 有必要在解析时去除换行符。这正是|- 所做的。

如果您真的想要 |,只需在输入字符串的末尾添加一个换行符,但请注意功能差异。

有关在 YAML 中包含多行字符串的各种方法的完整说明,请参阅 this answer

【讨论】:

  • 那个答案实际上被用作example of YAML's complexityFor example did you know there are nine ways to write a multi-line string in YAML with subtly different behaviour? Yeah :-/
  • @PanagiotisKanavos 你不会发现我在为 YAML 辩护。我不需要确信它过于复杂。
  • 只是一个巧合 - 这篇文章昨天在 Twitter 关于配置格式的讨论中重新出现。我刚刚意识到它链接到 那个 答案作为其复杂性的一个例子
猜你喜欢
  • 2016-10-22
  • 2011-04-16
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
相关资源
最近更新 更多