jinja2: including script, replacing {{variable}} and json encoding the result
<p>I'm attempting to build a json document using Jinja2 and the document has a nested script. The script contains <code>{{&lt;variables&gt;}}</code> that I need to replace along with non-json characters. Therefore, the script needs to be json-escaped afterwards using <code>json.dumps()</code>.</p>

<p><code>str = '{
  "nestedScript" : {% include "scripts/sc.ps1" | json %}
}'</code></p>

<p>The <code>escape</code> function isn't enough, since the finished product contains characters that are valid HTML, but not JSON.</p>

<p>I'm thinking something along the lines of:</p>

<p><code>str = '{
  "nestedScript" : {{ include("scripts/sc.ps1") | json}} %}
}'</code></p>

<p>using some a custom filter or something, but I can't seem to write the include function such that it also does variable replacement in the script. This is my script so far that I am including as a global:</p>

<h1>Complete example</h1>

<p>Folder structure:</p>

<pre><code> .
 âââ templates
     âââ test.json
     âââ scripts
     Â  Â  âââ script.ps1
</code></pre>

<p>template-file:</p>

<pre><code>test.json = '{
  "nestedScript" : {{ include("scripts/script.ps1") | json}}
}'
</code></pre>

<p>Script:</p>

<pre><code>loader = jinja2.FileSystemLoader("templates")
env = jinja2.Environment(loader=self.loader)
template = env.get_template("test.json")
template.render({
        'service_name': 'worker',
        'context_name': 'googlesellerratings',
    })
</code></pre>

<p>result:</p>

<pre><code>{
  "nestedScript" : "echo {{service_name}}"
}
</code></pre>

<p>Given the (incomplete) example it seems you are searching the <code>filter</code> tag.</p>

<p>First the script in a form that's actually runnable and defines a <code>json</code> filter in terms of <code>json.dumps()</code>:</p>

<pre><code>import json
import jinja2

loader = jinja2.FileSystemLoader('templates')
env = jinja2.Environment(loader=loader)
env.filters['json'] = json.dumps
template = env.get_template('test.json')
print(
    template.render({
        'service_name': 'worker',
        'context_name': 'googlesellerratings',
    })
)
</code></pre>

<p>The missing PowerShell script with characters that cause trouble if used as is in JSON (<code>"</code>):</p>

<pre><code>echo "{{service_name}}"
</code></pre>

<p>Now the solution for the <code>test.json</code> template:</p>

<pre><code>{
  "nestedScript" : {% filter json %}{% include "scripts/script.ps1" %}{% endfilter %}
}
</code></pre>

<p>And finally the printed result:</p>

<pre><code>{
  "nestedScript" : "echo \"worker\""
}
</code></pre>

python json jinja2