my variable file/data (i get this info from other source)
final_lst:
[
{
"service_role": "do_not_use",
"first_ip": "10.7.17.1",
"last_ip": "10.7.16.9",
"uid": "do_not_use"
},
{
"service_role": "role_a",
"first_ip": "10.7.17.10",
"last_ip": "10.7.17.25",
"uid": "role_a_range_01"
},
{
"service_role": "role_a",
"first_ip": "10.7.17.56",
"last_ip": "10.7.17.70",
"uid": "role_a_range_02"
}
]
test.j2:
{%- for item in final_lst %}
sr: {{item.service_role}}
ip: {{item.first_ip}}
{%- endfor -%}
my code: from jinja2 import Template , Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'),)
int_template = env.get_template('test.j2')
out = int_template.render(final_lst=final_lst)
print(out)
result:
sr: do_not_use
ip: 10.7.17.1
sr: role_a
fip: 10.7.17.10
sr: role_a
fip: 10.7.17.56
what i want to print is in json format like below
desired output:
[
{
"sr": "do_not_use",
"fip": "10.7.17.1"
},
{
"sr": "role_a",
"fip": "10.7.17.10"
},
{
"sr": "role_a",
"fip": "10.7.17.56"
}
]
i have a requirement to generate above output via jinja2 template. how can i get json format output anything that is rendered from jinja2 template
CodePudding user response:
I'd suggest not to generate json with means of template language. It is slower and much more error prone.
In your python code:
import json
from jinja2 import Template, Environment, FileSystemLoader
data = [
{
"service_role": "do_not_use",
"first_ip": "10.7.17.1",
"last_ip": "10.7.16.9",
"uid": "do_not_use"
},
{
"service_role": "role_a",
"first_ip": "10.7.17.10",
"last_ip": "10.7.17.25",
"uid": "role_a_range_01"
},
{
"service_role": "role_a",
"first_ip": "10.7.17.56",
"last_ip": "10.7.17.70",
"uid": "role_a_range_02"
}
]
data = [
{
'sr': elem['service_role'],
'fip': elem['first_ip'],
}
for elem in data
]
data_dump = json.dumps(data, indent=2)
env = Environment(loader=FileSystemLoader('templates'),)
int_template = env.get_template('test.j2')
out = int_template.render(data_dump=data_dump)
print(out)
In your template (test.j2
):
{{ data_dump }}
Don't do this!
If you insist on template solution:
[
{% for item in final_lst %}
{{ '{' }}
"sr": "{{ item.service_role }}",
"ip": "{{ item.first_ip }}"
{{ '}' }}
{% endfor %}
]
You can replace {%
with {%-
back to get compact representation (same applies to json.dumps
, just get rid of indent
parameter).