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

问题描述 投票:0回答:2

我有一个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)
python json jinja2
2个回答
0
投票

我取得了一些进步

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
#

0
投票

我想我有解决方案:

import json

from jinja2 import Template

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 {{ vlans[vlan].description }}
    name {{ vlans[vlan].name }}
#
{% endfor %}"""
)

print(vlan_template.render(vlans=vlans))
© www.soinside.com 2019 - 2024. All rights reserved.