String Quotes in YAML File

Submitted by leopathu on Sun, 05/08/2022 - 13:31
yaml

We all know YAML is "a human friendly data serialization standard for all programming languages". In Drupal 8, the old .INFO files are now gone and have been replaced by YAML files - pronounced “yamel” (rhymes with camel). The following will show the tricks on strings,

Strings : Strings in YAML can be wrapped both in single and double quotes. In some cases, they can also be unquoted:

A string in YAML

'A singled-quoted string in YAML'

"A double-quoted string in YAML"

 

Quotes are required when the string has Special/Reserved characters. Strings containing any of the following characters must be quoted. Although you can use double quotes, for these characters it is more convenient to use single quotes, which avoids having to escape any backslash \:

 

:, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \`

 

The double-quoted style provides a way to express arbitrary strings, by using \ to escape characters and sequences. For instance, it is very useful when you need to embed a \n or a Unicode character in a string.

 

"A double-quoted string in YAML\n"

 

Finally, there are other cases when the strings must be quoted, no matter if you're using single or double quotes:

  • When the string is true or false (otherwise, it would be treated as a boolean value);
  • When the string is null or ~ (otherwise, it would be considered as a null value);
  • When the string looks like a number, such as integers (e.g. 2, 14, etc.), floats (e.g. 2.6, 14.9) and exponential numbers (e.g. 12e7, etc.) (otherwise, it would be treated as a numeric value);
  • When the string looks like a date (e.g. 2014-12-31) (otherwise it would be automatically converted into a Unix timestamp).

 

Alternatively, strings can be written with the folded style, denoted by >, where each line break is replaced by a space:

 

>
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  without carriage returns.
Tags