我正在使用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
}
...
]
}
相似是不一樣的。它很可能是一本字典,其中的密鑰可以是任何(可排列)類型。 – Reti43
看來'item'是一個'string'而不是'dict'。 – AKS
所有的東西都是平等的,不是一個壞主意,看看你的JSON是否確實是有效的JSON。 http://jsonlint.com/說它不是。 –