簡體   English   中英

類型錯誤:字符串索引必須是整數 JSON 文件

[英]TypeError: string indices must be integers JSON File

不過,我對這一切都很陌生。 在我的代碼中,我試圖讓 Python 從一些免費天氣 API 中獲取天氣信息。然而,一切都會 go 根據計划,它會得到天氣 - 晴朗但是當涉及到整數時它會嚇壞,而且大多數所需信息的一部分是整數:溫度、濕度、風速等。這是它失敗的地方:

for result in data['main']:
  temp = result['temp']
  print('Temperature: '+temp)
  with open('data.txt', 'a') as f:
    f.write(' '+temp)
    f.write('\n')

該表看起來像:

'main': {'feels_like': 304.72,
          'humidity': 67,
          'pressure': 1011,
          'temp': 301.84,
          'temp_max': 303.85,
          'temp_min': 299.19},

主要是字典。

我試過添加[3]而不是['temp'\]

for result in data['main']:
  temp = result[3]
  print('Temperature: '+temp)
  with open('data.txt', 'a') as f:
    f.write(' '+temp)
    f.write('\n')

然而,output 是每個類別的前 3 個字母,例如TEM - TEMP / HUM - HUMIDITY

我知道它做了什么,但我只是信任某個網站。 我不知道有什么方法可以解決這個問題,很多網站只是 state,“更改 JSON 文件”,但我真的做不到。

我試過“Json.Loads”,但它指出,必須是“str、bytes 或 bytearray,而不是 dict”。

追溯

File "location", line 30, in <module>
    temp = result['temp']
TypeError: string indices must be integers

你的代碼:

for result in data['main']:
  temp = result[3]
  print('Temperature: '+temp)
  with open('data.txt', 'a') as f:
    f.write(' '+temp)
    f.write('\n')

遍歷 data['main'] 的鍵值。 換句話說,每次循環, result都是["feels_like", "humidity", "pressure", "temp", "temp_max", "temp_min"]列表中的一個值

你真正想做什么:

for result in data["main"]:
    if result == "temp":
        print("Temperature: %0.2f" % data["main"][result])
        with open("data.txt", "a") as f:
            f.write("  %0.2f\n" % data["main"][result])

甚至:

for field, result in data["main"].items():
    if field == "temp":
        print("Temperature: %0.2f" % result)
        with open("data.txt", "a") as f:
            f.write("  %0.2f\n" % result)

它從字典data["main"]中獲取鍵和值。

你可以做:

for key, result in data['main'].items():
    if key == 'temp':
       print(f'Temperature: result')
       #rest of your code

暫無
暫無

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

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