Anchors are used to define a reference to a value that can be used later in the document. Anchors start with an “&” character and are followed by a name that identifies the anchor. Here is an example of a YAML anchor:
first: &my_anchor name: John age: 30
In this example, “&my_anchor” defines an anchor that points to the dictionary that contains the “name” and “age” keys. The anchor name “my_anchor” can be any valid string.
To use the anchor reference later in the document, an alias is used. An alias starts with an “*” character and is followed by the name of the anchor. Here is an example of a YAML alias:
second: person: *my_anchor
In this example, the “person” key in the “second” dictionary is associated with an alias that points to the anchor defined earlier. The alias name “*my_anchor” must match the anchor name “&my_anchor” exactly.
Anchors and aliases can be used to define complex data structures and reduce duplication in the document. Here is an example that shows how anchors and aliases can be used to define multiple dictionaries with shared data:
&person name: John age: 30 first: *person location: city: New York state: NY second: *person location: city: San Francisco state: CA
In this example, the “&person” anchor defines a dictionary that contains the “name” and “age” keys. The “first” and “second” dictionaries both use the alias “*person” to reference the anchor, which means they will both contain the “name” and “age” keys. Each dictionary also has its own “location” dictionary.
Follow us on social media