最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Python3 YAML double curly brace no quotes - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question edited Mar 19 at 2:19 Adeva1 4941 silver badge8 bronze badges asked Mar 18 at 23:58 MaximMaxim 245 bronze badges 3
  • 1 I don't think the output you're looking for is valid YAML. Why do you want that particular output? – user2357112 Commented Mar 19 at 2:25
  • it is valid, YAML supports Jinja templating – Maxim Commented Mar 19 at 3:06
  • 1 @Maxim: Content user: {{ val }} is not valid for YAML in the sense that given content doesn't correspond to the key user 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". And yaml.dump() outputs data exactly in YAML format. – Tsyvarev Commented Mar 19 at 13:32
Add a comment  | 

1 Answer 1

Reset to default -1

To 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 }}
发布评论

评论列表(0)

  1. 暂无评论