krappold
krappold

Reputation: 27

How to fix an error thrown by python stating indices must be integers

I am pulling from an API in URL, and keep getting string indices must be integers error code thrown in python. I am wondering how to fix this? (The url is replaced with "url").

import urllib.request
import json
link = "url"
f = urllib.request.urlopen(link)
data = f.read()
print (str(data, 'utf-8'))
weather = json.loads(data)
print('/n')
print(weather["name"]["temp"])

Here's a sample of the json data:

{"coord":{"lon":-94.2166,"lat":36.4676},"weather":[{"id":600,"main":"Snow","description":"light snow","icon":"13n"}],"base":"stations","main":{"temp":262.83,"feels_like":255.36,"temp_min":262.04,"temp_max":263.71,"pressure":1025,"humidity":92},"visibility":10000,"wind":{"speed":6.17,"deg":30},"clouds":{"all":90},"dt":1613195709,"sys":{"type":1,"id":5695,"country":"US","sunrise":1613135272,"sunset":1613174070},"timezone":-21600,"id":0,"name":"Bella Vista","cod":200}

Upvotes: 0

Views: 33

Answers (1)

rhurwitz
rhurwitz

Reputation: 2747

Here is the data snippet you shared formatted in a way that it makes it easier to see what is going on. As you can see, while weather["name"] is valid, weather["name"]["temp"] is not, and that is what is producing the error you are seeing. Instead, weather["main"]["temp"] will display the temperature value in that dictionary.

weather = {'base': 'stations',
 'clouds': {'all': 90},
 'cod': 200,
 'coord': {'lat': 36.4676, 'lon': -94.2166},
 'dt': 1613195709,
 'id': 0,
 'main': {'feels_like': 255.36,
          'humidity': 92,
          'pressure': 1025,
          'temp': 262.83,
          'temp_max': 263.71,
          'temp_min': 262.04},
 'name': 'Bella Vista',
 'sys': {'country': 'US',
         'id': 5695,
         'sunrise': 1613135272,
         'sunset': 1613174070,
         'type': 1},
 'timezone': -21600,
 'visibility': 10000,
 'weather': [{'description': 'light snow',
              'icon': '13n',
              'id': 600,
              'main': 'Snow'}],
 'wind': {'deg': 30, 'speed': 6.17}}

Upvotes: 1

Related Questions