Reputation: 1023
I am writing a function to render json template using yaml config file.
It looks something like below :
render.py
:
if len(sys.argv) != 3:
print "usage: python render_template.py [yaml_file] [jinja_template_file]"
sys.exit(1)
with open(sys.argv[1], "r") as stream:
config = yaml.safe_load(stream)
with open(sys.argv[2], "r") as stream:
template_text = stream.read()
template = Template(template_text)
print template.render(config)
test.yaml
:
Application:
Hosts:
- a
- b
sample.json.templete
[{
"test1":
{
"objectName": "{{Application.Hosts}}",
}
}]
when I run
python ./render.py ./test.yaml ./sample.json.templete > sample.json
I get
[{
"test1":
{
"objectName": ['a' , 'b'],
}
}]
But since I am generating a json file I need
["a", "b"]
I.e. I want the list in double quotes. How do I best achieve it? How do I convert list with strings in single quotes to list with strings in double quotes?
Upvotes: 1
Views: 4032
Reputation: 1023
This would work
["{{Application.Hosts|join('","')}}"]
We don't need to make any custom filters
Upvotes: 1
Reputation: 1705
You could use a custom filter function in your template to format lists just the way you want them. You could then use this function for any list you want to format.
A good SO question/answer with some great info on creating a jinja2 filter to use with an iterable (e.g. your list) is available here
Then your json template can use the filter like this:
"objectName": "{{ Application.Hosts|format_list }}",
Your filter would most likely do something like this:
def format_list(my_list):
formatted_list = ", ".join(["%s" % item for item in my_list])
return "[%s]" % formatted_list
Upvotes: 1