Preserve leading whitespace on the first row of a YAML multiline string

Viewed 136

I have the below data that I wish to import:

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

I'd like to preserve the 7 leading spaces before Bb on the first row.

Is there a way I can do this?

I've put my hacky workaround up as a temporary answer, but I'd prefer a more elegant solution.

2 Answers

Per e.g. http://yaml-multiline.info/ you can add an indentation indicator in cases where it can't accurately be guessed from the first line:

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

The body here would be parsed to

"       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"

My current workaround is to add a non-indented first line:

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

And after the file has been read, I remove this line from the array.

But I'd much prefer not to have to compromise the YAML data in this way.

Related