Data Format Converter · Tutorial
How to see YAML anchors and merge keys as plain JSON
6 min readintermediateUpdated
Anchors and merge keys keep YAML short, but they make it hard to tell what each section really contains. This tutorial converts a typical database settings file to JSON, so every environment is spelled out in full and you can confirm which values were inherited and which were overridden.
What you need
- The Data Format Converter, set to YAML → JSON
- A YAML file with
&anchors,*aliasesor<<merge keys, or the sample from the Try it button
Steps
Paste the YAML
Paste your file into the left box. The sample defines shared database settings once under
defaults: &defaults, then reuses them indevelopment,testandproductionwith<<: *defaults.defaults: &defaults adapter: postgres host: localhost pool: 5 test: <<: *defaults database: shop_test pool: 2Read the expanded JSON
The right box shows every environment with all of its keys.
developmentnow containsadapter,hostandpoolfrom the defaults plus its owndatabase. There is no<<key left in the output, because the merge has been applied.Check the overrides
Keys written next to the merge key win over the shared ones. In the JSON,
testhas"pool": 2rather than 5, andproductionhas"host": "db.internal"and"pool": 20. If a value is not what you expected, the override is missing or misspelt in the YAML.Choose the output style
Keep 2 spaces for reading, or pick Minified in the Indent menu when you need the JSON on one line, for example to paste into an environment variable or a test fixture.
Copy or download
Press Copy, or Download to save
converted.json. Use it with a JSON Schema validator,jqor any program that does not understand YAML.
Try it yourself
Opens the Data Format Converter with this tutorial's sample loaded.
Common mistakes
- Expecting the anchor names in the JSON
- JSON has no references, so names like
&defaultsdisappear and the data is copied instead. Thedefaultsblock itself still appears because it is a normal key. - Putting the override above the merge key
- Order does not matter for overrides: a key written in the mapping always beats one brought in by
<<. If the value is wrong, check for typos in the key name instead. - Using an alias before its anchor
- An alias like
*defaultsmust come after&defaultsin the file. Otherwise the converter reports an unknown alias with its line and column.
Next steps
Go back to the Data Format Converter, or keep going with one of these:
FAQ
Does every YAML parser support merge keys?
Most do, including those used by Docker Compose, Rails and GitLab CI, but merge keys are a YAML 1.1 feature and a few strict YAML 1.2 parsers ignore them.
Can I convert the JSON back to YAML with anchors?
The Data Format Converter set to JSON → YAML writes the expanded data. Anchors have to be added back by hand.