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

新手上路,请多包涵

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

原文由 hullabaloon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

手动构建 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;例如,如果您的数据包括日期时间,您需要先将它们字符串化。

原文由 snakecharmerb 发布,翻译遵循 CC BY-SA 4.0 许可协议

我找到了一个要点并将其分叉以对 python 3.x 兼容性进行微不足道的更改,它对我来说非常有效:

https://gist.github.com/jerrydboonstra/bedb5ccbe6200b5d794447ed38aeb342

它有一个 example.json 文件充当带有“{{变量}}”标记的模板,以及一个 runner.py 组成模板的输出和输入数据结构。

在此处输入图像描述

原文由 jerryb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏