如何在Python/Flask中获取并展示JSON数组中重复键的所有数据
解决Flask展示全部JSON数组数据的问题
你的核心问题是当前代码只提取了JSON数组的第一个对象,要展示全部43条数据,只需要遍历整个数组,提取每个对象的指定字段即可,分后端代码和前端模板两部分修改:
1. 后端Flask代码修改
假设你原来的代码类似这样(仅取第一个元素):
from flask import Flask, render_template import requests app = Flask(__name__) @app.route('/') def index(): res = requests.get("你的API接口地址") match_data = res.json() # 仅提取第一个对象 single_match = match_data[0] return render_template('index.html', match=single_match)
修改为遍历整个数组,提取所需字段:
from flask import Flask, render_template import requests app = Flask(__name__) @app.route('/') def index(): try: # 请求API并解析JSON数组 res = requests.get("你的API接口地址") res.raise_for_status() # 捕获请求错误 all_matches = res.json() # 过滤出需要的字段,避免传递冗余数据 filtered_matches = [] for match in all_matches: # 检查必要字段是否存在,防止KeyError if {'home_team', 'away_team', 'commence_time'}.issubset(match.keys()): filtered_matches.append({ 'home': match['home_team'], 'away': match['away_team'], 'time': match['commence_time'] }) else: # 跳过字段不完整的数据 continue # 将处理后的数组传给模板 return render_template('index.html', matches=filtered_matches) except Exception as e: # 简单的错误处理 return f"数据加载失败:{str(e)}", 500
2. 前端模板(templates/index.html)修改
原来的模板只展示单个对象的内容,现在需要用Jinja2的循环语法遍历整个数组:
<!DOCTYPE html> <html> <head> <title>所有赛事信息</title> <style> .match-card { margin: 15px 0; padding: 10px; border: 1px solid #ddd; border-radius: 4px; } </style> </head> <body> <h1>全部赛事列表</h1> {% if matches %} {% for match in matches %} <div class="match-card"> <h3>{{ match.home }} vs {{ match.away }}</h3> <p>开赛时间:{{ match.time }}</p> </div> {% endfor %} {% else %} <p>暂无赛事数据</p> {% endif %} </body> </html>
关键说明
- 如果不需要提前过滤字段,也可以直接把
all_matches传给模板,在模板中直接用match.home_team提取字段,但提前过滤能减少数据传输量。 - 加入的
try-except和字段检查是为了避免API请求失败或数据格式异常导致页面崩溃,适合新手调试。
内容的提问来源于stack exchange,提问作者football_god91
相关产品推荐
相关产品推荐

