Advanced Features in YAML¶
Now that we're familiar with the basics of YAML, let's explore some advanced features like multiline strings, anchors and aliases, etc.
Multiline String in YAML¶
In YAML, you can create a multiline string using the pipe character |
or the greater than symbol >
.
Multiline String Using Greater Than Symbol¶
You can use >
if you want the line breaks to be stripped out. You'll still have one line break at the end. You can use >-
if you want to strip the line break at the end as well.
Tip
You can use YAML to JSON Converter Tool to see the resulting structure of the multiline string in YAML when it is parsed.
-
Multiline string using
>
:YAML will treat the string as:
-
Multiline string using
>-
:YAML will treat the string as:
Multiline String Using Pipe Character¶
You can use |
if you want the line breaks to be preserved as \n
. You can use |-
if you want to strip the line break at the end.
-
Multiline string using
|
:YAML will treat the string as:
-
Multiline string using
|-
:YAML will treat the string as:
Anchors and Aliases in YAML¶
YAML allows you to use anchors
and aliases
to create references to other parts of the document. This can be useful for avoiding repetition and simplifying complex structures.
Anchor¶
An anchor
is a name assigned to a specific value in the YAML document. It's indicated using the &
character followed by the anchor
name. For example:
In this example, the anchor name is my_list
and it refers to the list of values ["apple", "banana", "mango"]
.
Alias¶
An alias
is a reference to an anchor in the YAML document. It's indicated using the *
character followed by the anchor
name. For example:
In this example, the fruits
list contains an alias
to the my_list
anchor. When this YAML document is parsed, the alias
will be replaced with the corresponding anchor
value, resulting in the following list:
Using Anchor and Alias¶
Here's an example document that uses anchor
and alias
:
The above YAML is equivalent to the following YAML document:
Tip
You can covert the first document to JSON and then convert the resulting JSON back to YAML to see if they are actually equivalent.