Search code examples
pythonjsonjinja2

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


i have a json file vlans.json which contains the following

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

and based on this info i'm trying to generate a config using some jinja2 template that should generate an output like

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

any idea how the code for this one should look like?

so far i have this code, but nothing works...

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)

Solution

  • i made some progress

    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))
    

    and it prints

    #
    vlan 1
     description 
    #
    
    #
    vlan 2
     description 
    #
    

    unfortunately i dunno how to get to the output below

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