Python перестает выполняться после цикла for с JSON

#python #json #for-loop

#python #json #for-цикл

Вопрос:

Я делал учебник по JSON с Python, и я понял, что код не выполняется до конца.

Вот код:

 #
# Example file for parsing and processing JSON
#

import urllib.request  # instead of urllib2 like in Python 2.7
import json


def printResults(data):
    # Use the json module to load the string data into a dictionary
    theJSON = json.loads(data)

    # now we can access the contents of the JSON like any other Python object
    if "title" in theJSON["metadata"]:
        print(theJSON["metadata"]["title"])

    # output the number of events, plus the magnitude and each event name
    count = theJSON["metadata"]["count"]
    print(str(count)   " events recorded")

    # for each event, print the place where it occurred
    for i in theJSON["features"]:
        print(i["properties"]["place"])

    # # # code doesn't work from here # # #
    print("--------------n")

    # # print the events that only have a magnitude greater than 4
    for i in theJSON["features"]:
        if i["properties"]["mag"] >= 4.0:
            print("%2.1f" % i["properties"]["mag"], i["properties"]["place"])
    print("--------------n")

    # # print only the events where at least 1 person reported feeling something
    print("nnEvents that were felt:")
    for i in theJSON["features"]:
        feltReports = i["properties"]["felt"]
        if (feltReports != None):
            if (feltReports > 0):
                print("%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported "   str(feltReports)   " times")


def main():
    # define a variable to hold the source URL
    # In this case we'll use the free data feed from the USGS
    # This feed lists all earthquakes for the last day larger than Mag 2.5
    urlData = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"

    # Open the URL and read the data
    webUrl = urllib.request.urlopen(urlData)
    print("result code: "   str(webUrl.getcode()))
    if (webUrl.getcode() == 200):
        data = webUrl.read().decode("utf-8")
        # print out our customized results
        printResults(data)
    else:
        print("Received an error from server, cannot retrieve results "   str(webUrl.getcode()))


if __name__ == "__main__":
    main()
  

Код останавливается сразу после первого цикла:

     # for each event, print the place where it occurred
    for i in theJSON["features"]:
        print(i["properties"]["place"])
  

Я знаю, что это не отступ, потому что я могу запускать каждый цикл for отдельно, то есть второй цикл for запускается, если я прокомментирую первый.

Есть ли что-то, чего мне здесь не хватает? Спасибо!

Комментарии:

1. Я скопировал ваш код, и, похоже, он работает просто отлично. Как вы думаете, что не работает?

2. Ваш код работает хорошо. попробуйте проверить отступ вашего кода.

3. Возможно, это проблема с VS Code. На моей консоли отладки я получаю только первый цикл for. Я посмотрю, что я могу сделать! Спасибо, ребята!

Ответ №1:

Ваш код работает хорошо. Попробуйте проверить отступ вашего кода. Может быть, вам это нужно.

Вот ваш результат:

 result code: 200
USGS Magnitude 2.5  Earthquakes, Past Day
48 events recorded
112 km E of Chignik, Alaska
3 km SW of Indios, Puerto Rico
south of the Fiji Islands
10 km SSW of Port-Olry, Vanuatu
11 km E of Nueva Concepción, Guatemala
8 km ESE of La Parguera, Puerto Rico
27 km NW of Londres, Argentina
South Shetland Islands
23km NW of Ludlow, CA
56 km ENE of Pedro Bay, Alaska
4 km SE of Maria Antonia, Puerto Rico
2 km E of Magas Arriba, Puerto Rico
133 km S of Isangel, Vanuatu
155 km SSE of Sand Point, Alaska
8 km WSW of Volcano, Hawaii
9 km WSW of Volcano, Hawaii
5 km SSW of Pāhala, Hawaii
107 km SSE of Sand Point, Alaska
8 km WSW of Volcano, Hawaii
8 km WSW of Volcano, Hawaii
5 km E of La Parguera, Puerto Rico
4 km ESE of Maria Antonia, Puerto Rico
82 km SW of Kaktovik, Alaska
136 km SSE of Sand Point, Alaska
32 km E of Balmorhea, Texas
south of the Fiji Islands
16 km WNW of Clayton, Idaho
16 km WNW of Clayton, Idaho
16 km WNW of Clayton, Idaho
8km SW of Niland, CA
West Chile Rise
33 km SW of Ashkāsham, Afghanistan
23 km NNE of Golconda, Nevada
Southern Alaska
2 km S of Magas Arriba, Puerto Rico
123 km SE of Sand Point, Alaska
43 km SSW of Beaver, Alaska
66 km SE of Akutan, Alaska
7 km N of Nardin, Oklahoma
2 km SSE of Magas Arriba, Puerto Rico
38 km ESE of Nikolski, Alaska
82 km WNW of El Alto, Peru
northern Mid-Atlantic Ridge
West Chile Rise
7 km N of Nardin, Oklahoma
south of the Fiji Islands
113 km SSE of Sand Point, Alaska
northern Mid-Atlantic Ridge
--------------

4.6 south of the Fiji Islands
5.2 10 km SSW of Port-Olry, Vanuatu
4.2 11 km E of Nueva Concepción, Guatemala
5.0 27 km NW of Londres, Argentina
5.0 South Shetland Islands
4.3 133 km S of Isangel, Vanuatu
4.3 155 km SSE of Sand Point, Alaska
4.6 107 km SSE of Sand Point, Alaska
4.3 136 km SSE of Sand Point, Alaska
6.1 south of the Fiji Islands
4.7 West Chile Rise
4.4 33 km SW of Ashkāsham, Afghanistan
4.4 66 km SE of Akutan, Alaska
4.0 38 km ESE of Nikolski, Alaska
4.6 82 km WNW of El Alto, Peru
5.0 northern Mid-Atlantic Ridge
6.0 West Chile Rise
4.7 south of the Fiji Islands
4.0 113 km SSE of Sand Point, Alaska
5.3 northern Mid-Atlantic Ridge
--------------



Events that were felt:
5.2 10 km SSW of Port-Olry, Vanuatu  reported 3 times
4.2 11 km E of Nueva Concepción, Guatemala  reported 2 times
3.0 9 km WSW of Volcano, Hawaii  reported 9 times
2.8 5 km SSW of Pāhala, Hawaii  reported 1 times
2.7 8 km WSW of Volcano, Hawaii  reported 6 times
3.2 4 km ESE of Maria Antonia, Puerto Rico  reported 6 times
2.8 16 km WNW of Clayton, Idaho  reported 2 times
2.9 8km SW of Niland, CA  reported 1 times
3.3 7 km N of Nardin, Oklahoma  reported 6 times
3.0 2 km SSE of Magas Arriba, Puerto Rico  reported 1 times
3.2 7 km N of Nardin, Oklahoma  reported 2 times