Guide

YAML anchors, aliases, and merge keys

Understand YAML node reuse, why JSON does not retain references, and what to verify before converting merged mappings.

by Tools in a Tab · Published on · Reviewed on

Short answer

An anchor names a YAML node and an alias refers to that node again. Together they express reuse inside the representation graph.

defaults: &defaults
  timeout: 30
  retries: 3

worker:
  config: *defaults

&defaults declares the anchor and *defaults is the alias. The YAML 1.2.2 specification explains that anchor names are serialization details: resolved data contains nodes and references, not that name as an ordinary property.

What happens in JSON

JSON represents trees of objects and arrays without reference syntax. A converter must either expand the node, invent a reference convention, or reject the input. Expansion can duplicate data and cannot faithfully represent a cycle.

The YAML to JSON converter rejects anchors and aliases rather than hiding that choice. To produce JSON, replace references with explicit data first and check the resulting size.

The << merge key

Many parsers support << to combine mappings:

defaults: &defaults
  timeout: 30
  retries: 3

worker:
  <<: *defaults
  retries: 5

The expected result commonly keeps timeout: 30 and overrides retries with 5. However, the merge key is not part of the YAML 1.2 Core schema, so support and precedence depend on the parser and its extensions.

Migration checklist

  • Search for &, *, and << keys outside strings and comments.
  • Resolve references using the same parser as the original application.
  • Detect cycles before expanding.
  • Decide whether data duplication is acceptable.
  • Validate the JSON and compare overridden values afterward.

A safe conversion makes reference loss explicit instead of silently dropping it.