在 YAML 多行字符串的第一行保留前导空格

时间:2021-07-18 17:21:36

标签: yaml

我有以下数据要导入:

songs:
  -
    title: After Hours
    artist: The Velvet Underground
    body: |
             Bb        G7
      If you close the door
          Cm                  F
      The night could last forever
                Bb       G7
      Leave the sunshine out
          Cm           F
      And say hello to never

我想保留第一行 Bb 之前的 7 个前导空格。

有没有办法做到这一点?

我已经将我的hacky解决方法作为临时答案,但我更喜欢更优雅的解决方案。

2 个答案:

答案 0 :(得分:2)

例如http://yaml-multiline.info/ 您可以添加缩进指示符,以防无法从第一行准确猜出:

songs:
  -
    title: After Hours
    artist: The Velvet Underground
    body: |2
             Bb        G7
      If you close the door
          Cm                  F
      The night could last forever
                Bb       G7
      Leave the sunshine out
          Cm           F
      And say hello to never

此处的 body 将被解析为

"       Bb        G7\nIf you close the door\n    Cm                  F\nThe night could last forever\n          Bb       G7\nLeave the sunshine out\n    Cm           F\nAnd say hello to never\n"

答案 1 :(得分:0)

我目前的解决方法是添加一个非缩进的第一行:

    body: |
      BODY
             Bb        G7
      If you close the door
          Cm                  F
      The night could last forever

在读取文件后,我从数组中删除这一行。

但我更希望不必以这种方式破坏 YAML 数据。