How do you get JSON data that has multiple of the same key values in python/flask

Viewed 38

Hello to all I'm new to coding, and I'm not really sure how to word what I'm asking. I am using an API, I got the data I need in the form of a JSON file but the file has multiple of the same keys and I need to display all of those keys. Below is an example of the JSON data I need all of the home_team, away_team, and commence_time there are 43 items in the JSON file.

[
 {
  "id": "6cb8b70ef8969b46535e63a71e9500f5",
  "sport_key": "americanfootball_nfl",
  "sport_title": "NFL",
  "commence_time": "2022-11-22T01:15:00Z",
  "home_team": "Arizona Cardinals",
  "away_team": "San Francisco 49ers"
 },
 {
  "id": "febaaec689e0d22db53cb8eec2177048",
  "sport_key": "americanfootball_nfl",
  "sport_title": "NFL",
  "commence_time": "2022-11-24T17:30:00Z",
  "home_team": "Detroit Lions",
  "away_team": "Buffalo Bills"
 },
 {
  "id": "7105b806f4de825d7ed04c2a88ea7dc1",
  "sport_key": "americanfootball_nfl",
  "sport_title": "NFL",
  "commence_time": "2022-11-24T21:30:00Z",
  "home_team": "Dallas Cowboys",
  "away_team": "New York Giants"
 }
]

This is what I have so far for code:

from app import app
from flask import render_template, request, url_for, redirect
import requests


@app.route('/', methods=['GET', 'POST'])
def home_page():
    url = "https://odds.p.rapidapi.com/v4/sports/americanfootball_nfl/odds"
    querystring = {"regions":"us","oddsFormat":"decimal","markets":"h2h,spreads","dateFormat":"iso"}
    headers = {
,
        "X-RapidAPI-Host": "odds.p.rapidapi.com"
}
    response = requests.request("GET", url, headers=headers, params=querystring)
    # print(response.text)


    if response.ok:
        data = response.json()
        # print(data)
        nfl = {
            "Home_Team": data[0]['home_team'],
            "Away_Team": data[0]['away_team']
        }
        return render_template('index.html', nfl=nfl)
    return render_template('index.html', nfl=nfl)

and this is what I'm trying to display for all 43 items

any help would be greatly appreciated

1 Answers

Supposing that you have a list of items in your json response. If you iterate the items in your code rather than your template what you are end up doing is to render the template 43 times showing only one item.

One thing that you can do is to pass all the items and iterate them in the template

if response.ok:
    data = response.json()
return render_template('index.html', nfl=data) 

In your Template you have to iterate the values to access them:

{% for team in NFL %}
   {% for key, value in team.items() %}
       <h1>Key: {{key}}</h1>
       <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

flask template with for loop jinja2 example

Related