Jinja2 converting double quotes to single quotes

Hi:

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.

Sample hitting the issue:

output.json:

{
“keepDoubleQuotes”: [ {“name”: “value”} ],
“loseDoubleQuotes”: [{‘name2’: ‘value2nestedValue’}]
}

test/tasks/main.yml:

This is hard for me to follow where you have defined these variables, how about sharing everything in a gist?

https://gist.github.com/anonymous/1ca1385f46a688ed2561

The output I see is:
“loseDoubleQuotes”: [{‘name2’: ‘value2nestedValue’}]

What I expect to see is:
“loseDoubleQuotes”: [{“name2”: “value2nestedValue”}]

Thanks for looking.

Rob

RobL,

Can you use ansible’s regex_replace jinja filter in test.j2 to turn surrounding single quotes to double quotes? e.g.

regex_replace(‘[1]?(.*)['"]?$’,‘“\1”’)


~~~

{
    "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 \

See also ansible’s regex_filter


  1. '" ↩︎

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 :slight_smile:

Thank you! That fixed the problem.