March 2018 Archives
Strings in YAML - To Quote or not to Quote
+++ This article has been refurbished and moved to +++
www.yaml.info/learn/quote.html
(June 2020)
Old version:
This article covers scalar styles in YAML 1.1 and 1.2. It mostly works the same in both versions.
YAML is a data serialization language, and one design goal was that it's human friendly. It should be easy to read and edit, even if that makes parsing it harder.
Let's look at strings, specifically.
If you look at JSON, you have only one style to encode strings, and that's the double quoted style which doesn't allow literal linebreaks.
YAML files are used for many different purposes, and there are many types of strings, especially multiline strings. For each use case, you can choose the type of quoting (or no quoting) that makes the string readable and easy to edit.
This gives you lots of freedom, but you also have to learn using it to avoid mistakes.
The good news is, the YAML double quoted string works the same as in JSON, so if you know that already, you will be able to write correct YAML. (I should note, though, that it also depends on the processor you use, since not all are fully JSON compatible. The incompatible cases should be rare, though.)
You basically have five ways to express a string:
- Flow scalars (plain, single quoted, double quoted)
- Block Scalars (literal, folded)
Table of Contents:
- Quick comparison
- Flow Scalars
- Plain Scalar
- When not to use Plain Scalars
- Single quoted Scalar
- Double quoted Scalar
- Block Scalars
- Block Scalar Types
- Literal Block Scalar
- Folded Block Scalar
- Comments
- Empty Lines at the beginning
- Special Block Scalar Indicators
- Block Scalar Chomping
- Block Scalar Indenting
- Summary