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

标签 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))

最佳答案

手动构建 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 版本,使用 json 构造 json在 Python 的标准库中打包,然后在您的模板中呈现 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;例如,如果您的数据包括日期时间,您需要先将它们字符串化。

关于python - 如何使用 Jinja2 模板引擎生成 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48632585/

相关文章:

Python dll 扩展导入

python - 使用 pandas dataframe 中的 JSON 对象优化解析文件,其中某些行中可能缺少键

Java JSONObject 获取 child

wordpress - 如何在 woocommerce 中为不同类别存档页面调用不同模板

c++ - 从模板函数引用全局数据?

python - 如何从 Flask api 检索 flutter 中的图像

python - 将自定义函数添加到 Python 中的现有类中

python - 将 writerow 与数字一起使用

javascript - 如何使用 jQuery .each() - 我得到一个值,但它是错误的

html - Blogger.com : Changing Header to slideshow with HTML & Java