jinja2 で dict 内の文字列を ダブルクォーテーションで出力する
jinja2 で {"apple": 1, "banana": 2} といった dict を出力したら {'apple': 1, 'banana': 2} というシングルクォーテーションで出力されてしまったので,ダブルで出力する方法を調べました.
モノによっては yaml のパースやその後の処理でシングルクォーテーションだと失敗したりします.
私の場合,nuclio で怒られました.
解決策
template の j2 ファイル内の置き換える部分に | tojsonを追加したらいけました.
具体例
シングルクォーテーション
- template.j2
item: {{ content }} - replace.py
from jinja2 import Environment, FileSystemLoader # テンプレートファイルのあるディレクトリを指定 env = Environment(loader=FileSystemLoader('./')) template = env.get_template('template.j2') # データを渡してレンダリング data = { "content": [ { "apple": 1, "banana": 2, } ] } output = template.render(data) with open("output.yaml", "w") as f: print(output, file=f) - 結果
item: [{'apple': 1, 'banana': 2}]
シングルクォーテーションになっちゃう.
ダブルクォーテーション
| tojson を入れる.
- template.j2
item: {{ content | tojson }} - 結果
item: [{"apple": 1, "banana": 2}]
ダブルクォーテーションで出力できた.