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

时间:2018-02-05 22:34:28

标签: python json templates jinja2

我正在尝试从.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))

2 个答案:

答案 0 :(得分:4)

手动构建json会冒着意外生成无效json字符串的风险。使用Python标准库中的json包构造json更安全,然后在模板中渲染json。分别构造json也简化了模板。

>>> import 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'}}

>>> # 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"
  }
}

答案 1 :(得分:0)

我找到了答案。将列表压缩为'matches'变量并构造如下模板:

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


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