Iterate over json string items in jinja2

Question:

Hi I need to send data in string format to my jinja templates, and the render them. The only way I found is to format my data as JSON and send it as a string to the renderer. But I don´t know how to use it in the templates, it seems that the tojson filter it´s not for this purpose, because it keeps rendered a string.

to keep it simple I’m doing something similar to:

import json

a = {"a":1,"b":[1,2,3,4]}
response = json.dumps(a)

in template:

{{ response }}
{{ response|tojson }}

both give a string response, not a dict or an object that I can use to render based on the values

Asked By: efirvida

||

Answers:

You can import json to use it’s load function to load it into jinja.

from json import loads

environment = jinja2.Environment(whatever)
environment.filters['load'] = loads
{{ response|load }}

Reference:
Import a Python module into a Jinja template?

Answered By: walker
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.