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

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?


Solution 1:

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.

Solution 2:

I had the exact same issue, and found that using the HTML escape code works :, which is what I resorted to.

Solution 3:

Building on answers already provided in other comments: http://yaml.org/spec/1.2/spec.html#id2788097

And from this: https://yaml.org/spec/1.2/spec.html#id2776092

I found that with any quotes you can just use two colons to escape the colon special character. i.e. ::

So the description would become:

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

Updated from comment: It looks like swagger specifically doesn't like multi-line strings, and in the editor whether the quoted text is on two lines or one it shows up the same. So I would suggest keeping the double quoted text on one line, to avoid problems with colons. i.e.

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