Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iterating Help
#1
Hello,

I've been working with some open API from ESPN located here:
https://statsapi.web.nhl.com/api/v1/game.../feed/live

as you can see, this is a pretty convoluted json file

I honestly do not know where to start as I have never worked with json files at this magnitude.

I have had a few attempts using this script here:

import urllib.request
import json

with urllib.request.urlopen("https://statsapi.web.nhl.com/api/v1/game/2021020748/feed/live") as url:
    live = json.loads(url.read().decode())
for type in live['liveData']['plays']:
    
though I don't know how to get from this point. I have tried by using another for loop

for type2 in type['allPlays'];
    print(type2)
Reply
#2
(Jan-27-2022, 06:01 PM)Joeylax54 Wrote: I honestly do not know where to start

...and we can't help you because we don't know what you want to accomplish.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
The following code will get you the json data and save in a dictionary.
I added the display__dict function only to show the format of the dictionary.
It's not needed for any other reason, and can be removed.

import requests
import json

nhlstats = {}

def display_dict(dictname, level=0):
    indent = " " * (4 * level)
    for key, value in dictname.items():
        if isinstance(value, dict):
            print(f'\n{indent}{key}')
            level += 1
            display_dict(value, level)
        else:
            print(f'{indent}{key}: {value}')
        if level > 0:
            level -= 1

url = "https://statsapi.web.nhl.com/api/v1/game/2021020748/feed/live"
response = requests.get(url)
if response.status_code == 200:
    nhlstats = response.json()
    display_dict(nhlstats)
else:
    print(f"Unable to extract json from {url}")
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020