【发布时间】:2018-07-15 21:36:31
【问题描述】:
我正在尝试从 .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))
【问题讨论】:
标签: python json templates jinja2