A Non-Comprehensive Guide to YAML for Folks Who Like JSON Just Fine
YAML is a human friendly data serialization standard for all programming languages. — https://yaml.org
I don’t know precisely which humans YAML is friendly to but I’m not one of them.
And it looks like the people who run in my circles are also excluded.
{% tweet ‘https://twitter.com/chantastic/status/1359601176434544640?s=20’ %}
Mapping to JSON
Between Eleventy, GitHub Actions, and a recent foray into serverless, I’m using a more YAML. And I don’t understand it.
This is mapping for my JSON-acquainted brain.
Outline
- Comments
- Array of strings
- Array of objects — single value
- Array of objects — many values
- Object of keyed arrays of strings
- Object of keyed objects with mixed values
- Array of arrays with mixed values
- Nodes
- Sample GitHub Action
- Takeaways
- Resources and further reading
- Keep in touch
Comments
YAML
JSON
JSON doesn’t support comments.
Array of strings
Sequence of Scalars
YAML
JSON
Array of objects — single value
Mapping Scalars to Scalars
YAML
JSON
Array of objects — many values
Sequence of Mappings
YAML
JSON
This syntax confused the shit out of me.
This code is auto-formatted by prettier putting the dash and the first property on the same line.
YAML docs show the dash and first property on different lines which is much more legible.
Object of keyed arrays of strings
Mapping Scalars to Sequences
YAML
JSON
Object of keyed objects with mixed values
Mapping of Mappings
YAML
JSON
Array of arrays with mixed values
Sequence of Sequences
YAML
JSON
Nodes
YAML
JSON
No JSON equivalent.
But this is the output from the above YAML.
Sample GitHub Action
YAML
JSON
Takeaways
Complex types are inferred
The structures of complex types are hidden in YAML.
They get inferred by the structure of included data.
Keep a look out for -
and :
which indicate the containing structure.
Dash -
If you see a dash -
, it means you’re describing a single array item.
This means you’re in an array.
Colon :
If you see a color :
separating two values, it means your describing a key-value pair.
This means you’re in an object.
In the wild
Since YAML is used often for configuration, it’s likely that your root type is object
.
At least that’s the case for Markdown Frontmatter, GitHub Actions, and CloudFormation templates.
TODO
Sections I’d like to add:
- Multi-line strings
- Block scalar
- Block scalar, block chomping indicators
-
strip+
keep
https://stackoverflow.com/a/21699210
Resources and further reading
- Official YAML 1.2 Documentation at yaml.org
- YAML to JSON web converters