Patryk Gtfo
Patryk Gtfo

Reputation: 273

String of jinja2 python > Json

I Must set variables in json so... i trying to do

{{ {{ config['port'] }} * ({{ channel_id }} * 100) - 100 }}

but doesn't work

Someone help me ?

Upvotes: 1

Views: 1211

Answers (3)

Robᵩ
Robᵩ

Reputation: 168716

Here is a short sample demonstrating how to create a JSON string from a template. Note particularly the complex math expression inside a single set of {{ }} brackets.

# First, let's create JSON from a template
from jinja2 import Template
template = Template('''
    { "port_addr_{{channel_id}}" :
        {{ (config['port'] * channel_id * 100 ) - 100 }}
    }''')
jstring = template.render(channel_id=7, config={'port':5})

# Now test to confirm it's valid
import json
pdict = json.loads(jstring)
assert pdict['port_addr_7'] == 3400

Upvotes: 1

MKesper
MKesper

Reputation: 509

Just use one pair of {{ }} brackets:

{{ config['port'] * (channel_id * 100) - 100 }}

The brackets tell jinja "Insert this computed expression here".

Upvotes: 2

reptilicus
reptilicus

Reputation: 10397

probably have to escape it with safe, something like:

{{json_stuff | safe}}

Upvotes: 0

Related Questions