-
-
Notifications
You must be signed in to change notification settings - Fork 23
Segment: Anchors
When your YAML data contains Anchors and Aliases -- including YAML Merge Keys -- you can select them by their unique name. Note that an &
prefix must be used whether accessing the defining Anchor or any of its Aliases or Merge Keys. Despite a YAML Alias normally being prefixed with a *
rather than an &
in the YAML data, you must still access them with an &
prefix in this YAML Path segment type. Demarcating the Anchor segment with a []
pair is optional.
For example:
---
aliases:
- &reusable_value This value can be used multiple times
anchored_hash: &anchor1
with: child
nodes: and values
including: *reusable_value
non_anchored_hash:
<<: *anchor1
with: its
own: children
All of the Anchors and their Aliases in the sample data can be directly accessed as:
-
aliases[&reusable_value]
oraliases[&reusable_value]
-
&anchor1
or/&anchor1
-
&anchor1.&reusable_value
or/&anchor1/&reusable_value
-
non_anchored_hash.&reusable_value
or/non_anchored_hash/&reusable_value
-
non_anchored_hash.&anchor1
or/non_anchored_hash/&anchor1
-
non_anchored_hash.&anchor1.&reusable_value
or/non_anchored_hash/&anchor1/&reusable_value
YAML Merge Keys can be directly addressed using this segment type. In the sample YAML data above, &anchor1
is used as a YAML Merge Key in non_anchored_hash
. It can be directly accessed via a YAML Path like non_anchored_hash[&anchor1]
or /non_anchored_hash/&anchor1
.
Unless using a YAML Path to create or destroy a YAML Merge Key, there is limited use in reading from them, though it is possible. The query would return the original data from the source Anchored Hash. Be aware that doing so ignores any overrides of those key-value pairs in the immediate Hash! From the sample data above, these two queries demonstrate this important distinction:
$ yaml-get --query='/non_anchored_hash/with' sample.yaml
its
$ yaml-get --query='/non_anchored_hash/&anchor1/with' sample.yaml
child
This segment type is especially useful for selecting named anchor values from the typical aliases:
list, commonly used in YAML files to define a unified location for any scalar values that are used more than once elsewhere within the same YAML file. For example:
aliases:
- &anchorA Some value
- &anchorB Another value
- &anchorC True
- &anchorD 5280
You could select the value, Another value
, by using its array element index -- if you knew it -- or more simply by its known anchor name, like so: aliases[&anchorB]
or /aliases[&anchorB]
. Please note that the &
symbol is always required to indicate an Anchor name. Further, the []
pair is always required when selecting from an Array (AKA: sequence, list).