I’m trying to use the template module to create a JSON file.
I’m hitting an issue where some of my double-quotes are converting to single quotes. Is there a way to ensure that Jinja2 won’t do this conversion? Notice how output.json has double-quotes for the first variable but single-quotes for the second variable. I’ve tried various ways of quoting, both in the template and in values.json.
~~~
{
"keepDoubleQuotes": {{ keepDoubleQuotes | regex_replace('^[
I didn't test that the matching single quote is escaped with \
See also ansible's regex_filter"]?(.*)[
I didn't test that the matching single quote is escaped with \
See also ansible's regex_filter"]?$','"\1"') }},
"loseDoubleQuotes": {{ loseDoubleQuotes | regex_replace('^[
I didn't test that the matching single quote is escaped with \
See also ansible's regex_filter"]?(.*)[
I didn't test that the matching single quote is escaped with \
See also ansible's regex_filter"]?$','"\1"')}}
}
I didn’t test that the matching single quote is escaped with \
Just as a quick PSA, you can actually use YAML for parameters passed in to “-e @test/values” if you like.
In the above example, nestedVar is expressed as a string, but that string actually contains no quotes, so that’s why you are not seeing quotes there.
The easiest suggestion here if you are trying to write a datastructure as json, is to have a template that is exactly this:
{{ datastructure | to_json }}
And it will do the right thing and use the kind of quoting that JSON entails.
This also has the added benefit of keeping everything in nice pure datastructures and not having to write something in a format for a particular datastructure.
By no means should you have to worry about regex replacements to solve this, that would be horribly painful