How to escape colons and other special characters in a YAML string?

Gustave picture Gustave · Oct 7, 2015 · Viewed 78.1k times · Source

I have the following YAML fragment:

description: |
  "API for bean consuming applications.
  Examples: painted pony, lima bean"

Swagger editor interprets the colon (:) as a special character, despite the quotation marks.

According to the accepted answer to this question, the colon should not be treated as special character.

Is this a bug of Swagger or is an escape sequence needed to use the colon in quoted text literals?

I tried to find this out using the YAML specification but gave up.

How do I have to read that spec to answer the question?

Is there a difference between single quotes (') and double quotes (") in YAML?

Does the pipe (|) or the greater than (>) construction only influence the line break handling or the handling of special characters, too?

Answer

Anthon picture Anthon · Oct 7, 2015

I would consider this a bug in swagger, but I have seen problems in other editors e.g. when highlighting YAML.

When a string scalar is surrounded by single quotes '....' the only escaping within that string that can be done is inserting a double single quote to indicate a single quote:

'It''s a good question'

When double quotes, "....", go around a scalar string you use backslash (\) for escaping, and you have to escape at least the backslash and the double quotes. In addition you can escape other special characters like linefeed (\n) and escape an end-of-line by preceding it by a backslash.

The YAML spec says there is no way to escape characters inside literal scalars ( starting with |), so you cannot insert extra newlines, or other escape sequences withing these.

For the folded style (>), the escaping behaviour is as with literal scalars.

All string scalars except for plain scalars (those without any quotes or >/|) can contain : followed by space without problem, and if an editor interprets that differently, that is understandable (as full YAML parsing is expensive), but incorrect.