繁体   English   中英

如何使用 Jinja2 模板引擎生成 json

[英]How to generate json using Jinja2 Template Engine

我正在尝试从 .xlsx 文件生成一个 json 文件。

到目前为止,我能够从文件中获取数据,但我不确定如何使用 jinja2 将它们放在 json 上。 模板结构有问题。 我该如何解决这个问题?

输出应该是这样的

  "Matches": {    
    "1": {
      "time": "19:00",
      "teams": "Team 1 - Team 2"
    },
    "2": {
      "time": "21:00",
      "teams": "Team 3 - Team 4"
    },
    ...
    ...
    ...
  }

我的代码是这样的。 显然模板部分是错误的。

from openpyxl import load_workbook
from jinja2 import Template


start_coloumn_of_matches = 3
end_coloumn_of_matches = 20

wb = load_workbook(filename = 'myfile.xlsx')
sheet_ranges = wb['Sheet1']

keys = []
teams = []
times = []


for x in range(start_coloumn_of_matches, end_coloumn_of_matches + 1):
    team_column = 'A' + str(x)
    time_column = 'D' + str(x)
    teams.append(sheet_ranges[team_column].value)
    times.append(sheet_ranges[time_column].value)
    keys.append(x)



template = Template(''' 
"Matches": {
        {% for key in keys %}
      "{{key}}": 
        {% endfor %}
      {
        {% for team in teams %}
        "teams": "{{team}}",
        {% endfor %}
        {% for time in times %}
        "time": "{{time}}"
        {% endfor %}
        }

    }, 

    ''' )

print(template.render(teams = teams, times = times, keys = keys))

手动构建 json 存在意外生成无效 json 字符串的风险。 使用工具来执行此操作更安全,并且可以减少模板的混乱。

如果您使用的是 Jinja 2.9 或更高版本,您可以使用内置的tojson过滤器将 Python 对象*自动转换为 json。

>>> import pprint

>>> # Construct some test data
>>> matches = ['1', '2', '3']
>>> times = ['19:00', '21:00', '23:00']
>>> teams = ['Team 1 - Team 2', 'Team 3 - Team 4', 'Team 5 - Team 6']

>>> # Combine the data structures to match the required output
>>> match_data = [dict(zip(['time', 'team'], pair)) for pair in zip(times, teams)]
>>> combined = {x: y for x, y in zip(matches, match_data)}
>>> pprint.pprint(combined)
{'1': {'team': 'Team 1 - Team 2', 'time': '19:00'},
 '2': {'team': 'Team 3 - Team 4', 'time': '21:00'},
 '3': {'team': 'Team 5 - Team 6', 'time': '23:00'}}

>>> template = jinja2.Template("""{{ matches | tojson(indent=2) }}""")
>>> print(template.render(matches=combined))
{
  "1": {
    "team": "Team 1 - Team 2",
    "time": "19:00"
  },
  "2": {
    "team": "Team 3 - Team 4",
    "time": "21:00"
  },
  "3": {
    "team": "Team 5 - Team 6",
    "time": "23:00"
  }
}

对于较早的 Jinja 版本,使用 Python 标准库中的json包构建 json,然后在您的模板中呈现 json。

>>> import json    
>>> # Serialise our object as json; setting the indent argument gives
>>> # the pretty printed format that we want.
>>> jdata = json.dumps(combined,  indent=2) 
>>> print(jdata)
{
  "1": {
    "time": "19:00",
    "team": "Team 1 - Team 2"
  },
  "2": {
    "time": "21:00",
    "team": "Team 3 - Team 4"
  },
  "3": {
    "time": "23:00",
    "team": "Team 5 - Team 6"
  }
}

>>> # Pass the json to the template for rendering.
>>> template = jinja2.Template("""{{ matches }}""")
>>> print(template.render(matches=jdata))
{
  "1": {
    "time": "19:00",
    "team": "Team 1 - Team 2"
  },
  "2": {
    "time": "21:00",
    "team": "Team 3 - Team 4"
  },
  "3": {
    "time": "23:00",
    "team": "Team 5 - Team 6"
  }
}

* 过滤器只处理原语 AFAICT; 例如,如果您的数据包含日期时间,则您需要先对它们进行字符串化。

我找到了答案。 将列表压缩到 'matches' 变量中,并像这样构造模板:

template = Template(''' 
"Matches": {
        {% for key, team, time in matches %}
      "{{key}}": 
      {
        "teams": "{{team}}",
        "time": "{{time}}"
        },
            {% endfor %}
    }
    ''' )


print(template.render(matches=zip(keys, teams, times)))

我发现这个 Gist 对我有用,对 Python 3 进行了非常小的调整(为打印语句添加括号)。

https://gist.github.com/sevennineteen/4400462

它有一个example.json文件,用作带有“{{ variable }}”标记的模板,以及一个runner.py ,它组合了模板的输出和输入数据结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM