2016-09-17 61 views
-1

我試圖從json urlfile打印'temp'項目。問題是,我不能只需鍵入print(item['temp'] 如果我這樣做,我得到這個錯誤:無法打印來自json api的想要的項目

TypeError: string indices must be integers

所以我想我不得不使用一個整數,而不是,這是我做的。但是,當它 打印出結果,我得到這個:

「F C」

這沒有任何意義,無所謂我輸入的內容數量,我得到的形式結果2個字母。

下面的代碼:

import urllib.request 
import json 

url = urllib.request.urlopen("http://www.myweather2.com/developer/forecast.ashx?uac=fRnJKj3Xpi&output=json&query=SW1") 
readurl = url.read() 
json_obj = str(readurl, "utf-8") 
data = json.loads(json_obj) 

for item in data['weather']: 
    print(item[0]) 
+0

這是因爲'item'是一個字符串,而不是字典。他們是字典中的*鍵*。 –

+0

@MartijnPieters如何在這樣的列表中調用一個項目? – Vitalynx

回答

0

data['weather']字典,並直接通過一個字典循環在該字典產生的鍵。這裏每個鍵都是一個字符串。或者'curren_weather''forecast'。因此,item[0]需要每個鍵的第一個字母,所以你最終打印fc

>>> for item in data['weather']: 
...  print(item) 
... 
curren_weather 
forecast 
>>> for item in data['weather']: 
...  print(item[0]) 
... 
c 
f 

我想你要打印字典中被引用的名單列表的'temp'關鍵curren_weather代替:

for curr in data['weather']['curren_weather']: 
    print(curr['temp'] + curr['temp_unit']) 

我添加​​值太;以上輸出:

15c