2016-04-21 111 views
0

我正在使用Python編寫程序以提示輸入URL,使用urllib從該URL讀取JSON數據,然後解析並從JSON數據中提取評論計數,計算總和文件中的數字並輸入下面的總和。這裏是我的代碼:TypeError:字符串索引必須是JSON的整數

import urllib 
import json 

total = 0 
url = open("comments_42.json") 
print 'Retrieving', url 
#uh = urllib.urlopen(url) 
data = url.read() 
print 'Retrieved',len(data),'characters' 
#print data 

info = json.loads(data) 
print info 
print 'User count:', len(info) 


for item in info: 
    print item['count'] 
    total = total + item['count'] 

print total 

我收到的錯誤是:

TypeError: string indices must be integers" for "print item['count'] 

爲什麼他們必須是整數?我的Coursera老師也做了類似的事情。有什麼建議?

JSON文件中有這樣的結構:

{ 
    comments: [ 
    { 
     name: "Matthias" 
     count: 97 
    }, 
    { 
     name: "Geomer" 
     count: 97 
    } 
    ... 
    ] 
} 
+0

相似是不一樣的。它很可能是一本字典,其中的密鑰可以是任何(可排列)類型。 – Reti43

+0

看來'item'是一個'string'而不是'dict'。 – AKS

+0

所有的東西都是平等的,不是一個壞主意,看看你的JSON是否確實是有效的JSON。 http://jsonlint.com/說它不是。 –

回答

0

錯誤"TypeError: string indices must be integers" for "print item['count']"item是一個字符串;在這種情況下,它是一個字典鍵。

我還沒有看到你的JSON,但如果你的「comments_42.json」爲this dataset,試試下面的代碼:

total = 0 
for item in info["comments"]: 
    print item['count'] 
    total += item["count"] 

我發現它here(也許有人解決了這個挑戰,或者不管它是什麼,並上傳解決方案)

+0

我剛剛嘗試過,並且得到相同的錯誤。 – abadila123

+0

好吧,所以我嘗試了你的代碼,它會去「ImportError:no module named requests。」 – abadila123

+0

@ abadila123'requests'只需要在線獲取數據集。您似乎已將其放在您的計算機上,因此您可以將其刪除。檢查我更新的答案。順便說一句。我們可以在一分鐘內解決這個問題,如果你在你的問題中發佈了json或其中的一部分 – jDo

0

它告訴你item是一個字符串,這意味着你的JSON結構不像你在課程中使用的那樣。例如

info = ['the', 'items', 'inside', 'this', 'list', 'are', 'strings'] 

for item in info: 
    # Items here are strings (the, information, etc) 
    print(items) # this will print each word in the list 




info = {'sentence': 'the', 'items', 'inside', 'this', 'list', 'are', 'strings'} 

for items in info: 
    # This is a dictionary, which can be addressed by the key name 
    print(items['sentence']) # this is what you're expecting, because 'sentence' is a dictionary key. 

如果你把你的JSON響應原來的問題,我們可以幫助您瞭解如何獲取你想要的物品。

相關問題