Я не могу заставить Python печатать данные из JSON, пропустив его через цикл for.
Я хотел бы запустить цикл for через файл JSON и напечатать его значениеключ 'familyName' для каждого элемента в списке.
Когда я печатаю значение ключа 'familyName' для одного элемента в списке ..
print((results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["familyName"])
.. Я получаюрезультат, который я ищу:
Hamilton
Однако, когда я пытаюсь использовать цикл for, чтобы получить 'familyName' для каждого элемента в списке ..
for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
print([0]["Driver"]["familyName"])
..это выдает ошибку.
Traceback (most recent call last):
File "D:\Python\F1App\f1.py", line 58, in <module>
getUserInput(input('Please enter your selection: '))
File "D:\Python\F1App\f1.py", line 32, in getUserInput
print([0]["Driver"]["givenName"])
TypeError: list indices must be integers or slices, not str
Это смущает меня, потому что это работает, когда печатается самостоятельно, но не как цикл for.Я предполагаю, что использовал неправильный синтаксис.
Заранее спасибо.
Вот ссылка на файл JSON: http://ergast.com/api/f1/current/driverStandings.json
Вот весь мой кодесли требуется:
import json
import requests
r = requests.get('http://ergast.com/api/f1/current/driverStandings.json')
results_information = r.json()
q = requests.get('http://ergast.com/api/f1/current/next.json')
next_circuit = q.json()
s = requests.get('http://ergast.com/api/f1/current/last.json')
last_circuit = s.json()
status = True
def getUserInput(number):
if number == '1':
print()
print("The leader of the driver standings for the current F1 season is:")
print((results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["givenName"]) + " " + (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["familyName"]))
elif number == '2':
print()
print("The leader of the constructor standings for the current F1 season is:")
print(results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Constructors"][0]["name"])
elif number == '3':
print()
print(('The next race of the current season will be the ') + (next_circuit['MRData']['RaceTable']['Races'][0]['raceName']))
elif number == '4':
print()
print(('The previous race of the current season was the ') + (last_circuit['MRData']['RaceTable']['Races'][0]['raceName']))
elif number == '5':
print()
print('Here are the driver standings for the current F1 season:')
for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
print([0]["Driver"]["familyName"])
elif number.lower() == 'e':
print()
print('Goodbye.')
print()
exit()
else:
print()
print('Please enter a valid input.')
print()
while status == True:
print('----------------------------')
print('Welcome to the F1 Python App')
print('----------------------------')
print()
print('------------MENU------------')
print('----------------------------')
print('Enter \'1\' for leader of the driver standings for the current F1 season.')
print('Enter \'2\' for leader of the constructor standings for the current F1 season.')
print('Enter \'3\' for location of the upcoming race circuit in the current F1 season.')
print('Enter \'4\' for location of the previous race circuit in the current F1 season.')
print('Enter \'5\' for the driver standings for the current F1 season.')
print('Enter \'E\' to exit the application.')
print()
getUserInput(input('Please enter your selection: '))