0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Tips】jinja2 で dict 内の文字列を ダブルクォーテーションで出力する

0
Last updated at Posted at 2025-05-27

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}]
    

ダブルクォーテーションで出力できた.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?