通过JSON运行for循环的问题

时间:2019-06-14 17:22:11

标签: python json string dictionary for-loop

我似乎无法让Python通过for循环运行来从JSON打印数据。

我想在JSON文件中运行一个for循环,并让其打印列表中每个项目的'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: '))

3 个答案:

答案 0 :(得分:1)

您应该注意错误消息告诉您的那行。我想你的意思是:

Echo

答案 1 :(得分:0)

您需要像这样使用变量i而不是[0]

for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
            print(i["Driver"]["familyName"])

原因是results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]的值 每次迭代时,它们都存储在变量i中。然后,您通过i["Driver"]["familyName"]访问它。您不需要[0],因为for循环已在列表中进行迭代。

答案 2 :(得分:-2)

您已经在第一行中显示了

(results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["familyName"]

等于字符串

Hamilton

因此,您的错误是由于尝试遍历该字符串而不是包含该字符串的列表而发生的。

这就像在说

for i in 'Hamilton'

相反,您应该使用原始清单:

for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
            print([0]["Driver"])