I have a python script that generates yaml files with pyyaml and I need something like this in the output:
key: {{- something }}
When I try to add this in my dictionary object
{ "key": "{{- something }}" }
the output will be this:
key: '{{- something }}'
Is there a workaround where I can put braces into the dictionary value? Thanks!
I tried string formatting or putting the {{- something }}
into a variable but it always prints it with the ''
marks.
This is not possible with PyYAML or any conforming YAML implementation.
This:
key: {{- something }}
is invalid YAML because {
starts a flow mapping, while -
starts a block sequence item. While you can nest flow mappings, you cannot put a block sequence item into a flow mapping.
You cannot use a YAML implementation to create invalid YAML, as the point of a YAML implementation is to always output valid YAML.
You are probably not actually generating YAML files, but Jinja templates that compile to YAML files (guessing from the fact that {{- something}}
is a typical Jinja construct). A YAML implementation cannot help you generate files that need to be processed by a templating engine to become valid YAML files.
There are some workarounds. For example, you could output
key: _something_
and then post-process the output to replace _something_
with {{- something}}
. I chose _something_
because that's a format PyYAML does not quote by default.