Generating YAML? Generate JSON instead
✦ 2024-08-31
YAML is difficult. It’s so difficult that certain YAML flaws have names. The Norway Problem (archive) being the most infamous of them all.
Templating YAML is even more difficult. Whitespace is meaningful. You’ve got to manage whitespace in your templating language and whitespace in the YAML you’re generating.
{- range ['foo', 'bar', 'baz'] }
- { . } {# the space before the `-` on this line matters! }
{ end -}
In steps JSON.
JSON is a strict subset of YAML. At least it has been since YAML 1.2 back in 2009 (archive). Any valid JSON document is also a valid YAML document.
So generate JSON instead.
<%=
require 'json'
[
'foo',
'bar',
'baz'
].to_json
%>
And as always, don’t interpolate it.