如何使用 jinja2 和 python 中的 json 文件生成配置

how to generate config using jinja2 and a json file in python

我有一个 json 文件 vlans.json,其中包含以下内容

{"1": {"description": "default", "name": "default"}, "2": {"description": "ilo", "name": "ILO"}}

基于此信息,我正在尝试使用一些 jinja2 模板生成一个配置,该模板应生成类似

的输出
#
vlan 1
 description default
 name default
#
vlan 2
 description ilo
 name ilo
#

知道这个代码应该是什么样子吗?

到目前为止我有这段代码,但没有任何效果...

from jinja2 import Template
import json

vlans_file = "vlans.json"

vlan_template = '''
vlan {{ vlans.id }}
 description {{ vlans.description }}
 name {{ vlans.name }}
 #
'''

with open(vlans_file) as json_file:
    vlans = json.load(json_file)
    for key in vlans:
        vlan_config = vlan_template.render(vlans)

我取得了一些进步

from jinja2 import Template
import json

vlans_file = "vlans.json"

with open(vlans_file) as json_file:
    vlans = json.load(json_file)

vlan_template = Template('''
{% for vlan in vlans %}
#
vlan {{ vlan }}
 description {{ value }}
#
{% endfor %}

''')

print(vlan_template.render(vlans = vlans))

并打印

#
vlan 1
 description 
#

#
vlan 2
 description 
#

不幸的是我不知道如何得到下面的输出

#
vlan 1
 description default
 name default
#
vlan 2
 description ilo
 name ilo
#