【问题标题】:How to split long strings over multiple lines in yaml without introducing whitespace characters如何在 yaml 中将长字符串拆分为多行而不引入空白字符
【发布时间】:2021-11-12 07:31:19
【问题描述】:

在 yaml 中,有多种方法可以将长字符串格式化为多行。例如:

输入:

example:
  string1: An example of a long string that is split across 
    two lines

输出(作为 JSON):

{
  "example": {
    "string1": "An example of a long string that is split across two lines"
   }
}

或者使用显式折叠语法:

example:
  string1: >
    An example of a long string that is split across
    two lines

输出:

{
  "example": {
    "string1": "An example of a long string that is split across two lines"
   }
}

或者使用文字语法:

example:
  string1: |
    An example of a long string that is split across
    two lines

输出:

{
  "example": {
    "string1": "An example of a long string that is split across\ntwo lines"
   }
}

在我能找到的所有示例中,似乎生成的字符串将在每行之间插入一个空格或换行符。但是,我想在几行上写一个很长的 yaml 字符串,在结果行中没有插入空格。这可能吗?

我的要求:

example:
  string1: Oneverylongunbrokenlinethatmustnotcon
    tainanyresultingwhitespaceintheoutput

期望的输出:

{
  "example": {
    "string1": "Oneverylongunbrokenlinethatmustnotcontainanyresultingwhitespaceintheoutput"
   }
}

这样的语法存在吗?

【问题讨论】:

    标签: yaml


    【解决方案1】:

    您省略了双引号标量样式,这正是您所需要的:

    example:
      string1: "Oneverylongunbrokenlinethatmustnotcon\
        tainanyresultingwhitespaceintheoutput"
    

    双引号标量是 YAML 中唯一允许在任意位置分成多行的标量样式。这是通过转义换行符来完成的。如果你不逃避换行符,你会得到一个空格,就像大多数其他标量样式一样。

    这不适用于任何其他样式,因为只有双引号标量处理转义序列。

    【讨论】:

    • 这是完美的。太感谢了。我通读了 Yaml 1.2 规范,看不到这种变化,所以期待答案是“不,这是不可能的”。
    猜你喜欢
    • 2011-04-16
    • 2018-02-14
    • 2017-08-01
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多