2016-09-16 79 views
0

我有下面的代碼,我正在作爲AI項目的一部分工作。我正在尋找獲取標籤,用戶搜索並返回一個標題的帖子的網址。使用Python請求和解析JSON

from meya import Component 
import requests 
import json 

API_URL = "https://e621.net/post/index.json?limit=1&tags=rating:s+order:random+{tag}" 

class e621_call(Component): 
"""Produces a e621 post based on the user's tags.""" 

def start(self): 
    tag = self.properties.get('tag') or \ 
     self.db.flow.get('tag') 

    response = requests.get(API_URL.format(tag=tag)) 

    img = response.json()['file_url'] 

    message = self.create_message(text=img) 

    return self.respond(message=message, action="next") 

一切都很好,直到我給你IMG的FILE_URL值,它會彈出一個

TypeError: list indices must be integers, not str 

爲了記錄在案,我使用meya.ai這一點,和包不是問題

+0

返回的JSON數據是一個列表,而不是一個字典。 –

回答

1

您的API返回列表中的字典。首先進入列表,然後你可以用字典來做你想做的事情。

response = requests.get(API_URL) 
foo = json.loads(response.content) 
file_url = foo[0].get('file_url') 

如果您打算讓多個字典在列表中返回,您可以循環遍歷foo並找到多個url。

for d in foo: 
    print d.get('file_url') 

而且,我寧願不使用以.json()(正如你可能已經注意到我並沒有包括在我的答案),因爲這樣你可以正確地繼續之前請檢查STATUS_CODE第一。否則,如果你得到一個404或500例如,你會得到錯誤。

if response.status_code == 200: 
    do stuff here 
else: 
    print "Something is wrong" 
0

我找到了一個臨時workthrough,更換response.json()['file_url']response.json()[0]['file_url']工作在AI罰款,儘管它仍然給我的錯誤。