簡體   English   中英

如何修復 python 引發的錯誤,指出索引必須是整數

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

我從 URL 中的 API 中提取,並不斷獲取字符串索引必須是在 python 中拋出的整數錯誤代碼。 我想知道如何解決這個問題? (將 url 替換為“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"])

這是 json 數據的示例:

{"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}

這是您共享的數據片段,其格式可以更輕松地查看正在發生的事情。 如您所見,雖然weather["name"]有效,但weather["name"]["temp"]無效,這就是產生您所看到的錯誤的原因。 相反, weather["main"]["temp"]將顯示該字典中的溫度值。

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}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM