I need help with outputting a dictionary value without quotes that contains double curly braces. This yaml file will be used for ansible which supports jinja.
import yaml
data = {
'user' : '{{ val }}'
}
print(yaml.dump(data))
I need the output of this to be user: {{ val }}
without quotes. No matter what I try, the output is user: '{{ val }}'
. This output needs to be single line / no block indentation.
I need help with outputting a dictionary value without quotes that contains double curly braces. This yaml file will be used for ansible which supports jinja.
import yaml
data = {
'user' : '{{ val }}'
}
print(yaml.dump(data))
I need the output of this to be user: {{ val }}
without quotes. No matter what I try, the output is user: '{{ val }}'
. This output needs to be single line / no block indentation.
1 Answer
Reset to default -1To determine how a given scalar value is emitted pyyaml calls yaml.emitter.Emitter.choose_scalar_style
, which returns an empty string if the scalar value is to be emitted as is. Since the default dumper inherits this method, you can override it to make it always return an empty string so that even a string with special characters would be emitted without quotes:
import yaml
class PlainDumper(yaml.Dumper):
def choose_scalar_style(self):
return ''
data = {
'user' : '{{ val }}'
}
print(yaml.dump(data, Dumper=PlainDumper))
This outputs:
user: {{ val }}
user: {{ val }}
is not valid for YAML in the sense that given content doesn't correspond to the keyuser
mapped to the string value{{ val }}
. You may name the resulting format as "YAML which support Jinja templating", but this format is incompatible with the format named "YAML". Andyaml.dump()
outputs data exactly in YAML format. – Tsyvarev Commented Mar 19 at 13:32