jinja 2嵌套字典到yaml

时间:2016-04-26 18:10:49

标签: python jinja2

我正在尝试使用jinja2将嵌套字典输出到yaml文件。但是我不确定如何访问嵌套的dicts。 使用平坦的数据字典,我可以使用下面的内容。

 - request:
        path: {{ path }}
        headers:
          origin: 'somedomain.com'
          user-agent: 'agent'
          referer: 'some.domain.com'
          authority: 'somedomain.com'
        data:
          {% for key, value in data.items() -%}
          {{ key }}: '{{ value }}'
          {%- endfor %}
      response:
        content:
          file: {{ content }}

但是如下面的嵌套字典如何在底部实现输出?

{'toplevelkey1': {'nestedkey1': 'value1', 'nestedkey2': 123, 'nestedkey3': '55',
                 'nestedkey4': 1560}, 'toplevelkey34': 'df',
 'toplevelkey2': {'somekey12': 68, 'somekey58': False, 'somekey48': 3, 'somekey38': 'ADF',
                              'somekey39': 'St'}, 'toplevel34': 'T',
 'toplevel8': {'key33': 68, 'key94': 3, 'key83': 'T', 'key84': 'dog'}}

必需的输出

   - request:
    path: /some/path
    headers:
      origin: 'somedomain.com'
      user-agent: 'agent'
      referer: 'somedomain.com'
      authority: 'somedomain.com'
    data:
      toplevelkey1: 
        nestedkey1: 'value1'
        nestedkey2: '123
        ....      : ....
      toplevel34: 'T'
      toplevelkey2:
        'somekey12': 68
         .....     :  .....
  response:
    content:
      file: address.json

1 个答案:

答案 0 :(得分:4)

我会介绍一个自定义递归"漂亮的打印"过滤器,它将支持任何级别的嵌套:

def pretty(d, indent=10, result=""):
    for key, value in d.iteritems():
        result += " " * indent + str(key)
        if isinstance(value, dict):
            result = pretty(value, indent + 2, result + "\n")
        else:
            result += ": " + str(value) + "\n"
    return result

env.filters['pretty'] = pretty

并在模板中使用它:

{{ data|pretty }}