Search code examples
c#yamlyamldotnet

Is this a valid Yaml list? How do I make YamlDotNet read it?


I have old C++ code which manually parses YAML and has a large number of unit tests. I am converting it over to C# using YamlDotNet. But one of the features of the old code was that it could handle a bit of variability in the lists. For example, consider the following list...

images:
  - image01.png 
  - image02.png
  - image03.png

The old parsing code could handle the case where there is no space between the '-' character and the item. So it can also read this with no problem.

images:
  - image01.png 
  -image02.png
  - image03.png

Unfortunately YamlDotNet does not parse this. I was converting the unit test that specifically verifies this and YamlDotNet throws a YamlDotnet.Core.SemanticErrorException with this message

While parsing a block collection, did not find expected '-' indicator

But if I then go in and put the space back between the '-' and the "image02.png", it reads the yaml perfectly.

So my questions are

  1. Is this technically even valid YAML? That is, should the list above always cause a fault? If not, I'll just get rid of the unit test.
  2. But if it is valid YAML, is there an option I can pass to the YamlDotNet Deserializer to handle it?

Solution

  • In YAML,

    • - image01.png (with the space) encodes the string image01.png as an array item, while
    • -image02.png encodes just the string -image02.png (including the dash), and as such invalidates your document due to its misplacement within the surrounding array context.

    So, the answer to your questions is: No, it's not valid YAML. See the YAML specs under section 2.1. Collections:

    Block sequences indicate each entry with a dash and space (“- ”).