![](/img/trans.png)
[英]Can I use an object (an instance of a class) as a dictionary key in Python?
[英]Can I use the a dictionary key in an API call? (Python)
我認為這沒有問題,但是我確實遇到了這段代碼的麻煩,似乎無法提出解決方案。
我有一本字典,其關鍵字是專有名稱,例如John Green,並且我正在使用Sunlight Foundation的API來檢索有關大會成員的信息( 請在此處檢查 )。 現在,我需要使用名稱和姓氏進行請求,因此我的代碼如下所示:
for key in my_dict:
query_params2 = { 'apikey': 'xxxxxxxxxxx',
'firstname' : key.split()[0],
'lastname' : key.split()[-1]
}
endpoint2 = "http://services.sunlightlabs.com/api/legislators.get.json"
resp2 = requests.get(endpoint2, params = query_params2)
data2 = resp2.json().decode('utf-8')
print data2['response']['legislator']['bioguide_id']
這給出了一些我無法真正解釋的錯誤:
Traceback (most recent call last):
File "my_program.py", line 102, in <module>
data = resp.json()
File "//anaconda/lib/python2.7/site-packages/requests/models.py", line 741, in json
return json.loads(self.text, **kwargs)
File "//anaconda/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "//anaconda/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "//anaconda/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
我猜想它與編碼有關,但是我不確定該如何解決。
不用說,如果我手動輸入名稱和姓氏,該請求就可以正常工作。
有人可以幫忙嗎? 非常感謝!
這與編碼無關。 答案根本不是JSON。 當我用“ John”和“ Green”嘗試您的代碼時,我收到一個400 Bad Request
,響應的內容是“ No Such Object Exists”。
在Web界面中嘗試John Green也會帶來一個空洞的答案。 API文檔中的URL也與示例中的URL不同。
以下為我工作(再次沒有約翰·格林):
import requests
LEGISLATORS_URL = 'https://congress.api.sunlightfoundation.com/legislators'
API_KEY = 'xxxx'
def main():
names = [('John', 'Green'), ('John', 'Kerry')]
for first_name, last_name in names:
print 'Checking', first_name, last_name
response = requests.get(
LEGISLATORS_URL,
params={
'apikey': API_KEY,
'first_name': first_name,
'last_name': last_name,
'all_legislators': 'true'
}
).json()
print response['count']
if response['count'] > 0:
print response['results'][0]['bioguide_id']
if __name__ == '__main__':
main()
輸出:
Checking John Green
0
Checking John Kerry
1
K000148
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.