行..我其實是如此努力通過自己想出解決辦法,但我似乎無法弄清楚。我不斷收到KeyError異常:「數據」巨蟒
我試圖訪問一個JSON文件,並打印出一些東西,我想。
我想要訪問的網址是: https://www.reddit.com/user/clockwork8.json
所以這裏的交易
我現在所擁有的:
import urllib, json, unicodedata
username1 = raw_input('Username: ')
url1 = "https://www.reddit.com/user/clockwork8"
response = urllib.urlopen(url1)
data = json.loads(response.read())
在代碼的頂部,和我嘗試了以下兩種選擇:
for number in data["data"]["children"]:
for fordata in data["data"]["children"][number]:
if fordata == "data":
for key in data["data"]["children"][post][fordata]:
if key == "score":
print data["data"]["children"][post]["data"][key].encode('ascii')
if key == "link_url":
print data["data"]["children"][post]["data"][key].encode('ascii')
其中給我這個錯誤:
for fordata in data["data"]["children"][number]:
TypeError: list indices must be integers, not dict
所以,我想這一點:
for a in range(len(data['data']['children'])):
print data['data']['children'][a]['data']['score'].encode('ascii')
,現在它給了我這個錯誤:
for a in range(len(data['data']['children'])):
KeyError: 'data'
任何想法是什麼問題..?
在'data'你要哪些對象?使用你的代碼我得到'25'的結果 – davedwards
也許你想在數據['data'] ['children']]中打印d ['data'] ['score']爲d?給出25'scores':[3, 1, 2, 1, 0, 2, 1, 0, -3, 9, 1, 3, 2, 2, 4, 2, 1, 2, 16, -1, 58, 3, 1, 0, -18] – davedwards