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 · Updated

Short answer

An anchor names a YAML node and an alias refers to that node again. Together they express reuse inside the representation graph. JSON has no equivalent reference syntax, so conversion requires explicit expansion or rejection. Do not remove & and * alone: that can turn references into unrelated text.

For a conversion task, jump to the explicit merge replacement.

An anchor and an alias

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

Under the YAML 1.1 merge-key extension, worker receives timeout: 30 and keeps its explicit retries: 5. An explicit key wins over a merged key. The merge key is not part of YAML 1.2 Core, so confirm whether the original parser enables that extension. This site’s converter rejects unquoted << keys as well as anchors and aliases.

Replace the merge with explicit data

For this small, acyclic example, replace the merge with the values it resolves to, keeping the override:

defaults:
  timeout: 30
  retries: 3

worker:
  timeout: 30
  retries: 5

Paste this replacement into the YAML to JSON converter. Check that defaults.retries remains 3, while worker.retries is 5 and worker.timeout is 30. The two objects now hold independent values.

This is not the same structure as the first alias example: there, the reused mapping belongs under worker.config; a merge inserts properties directly under worker. For larger files, resolve with the application’s parser and inspect its output before copying values. Expansion is not safe for cycles and can greatly increase the size of repeated data.

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.