我可以在API调用中使用字典键吗?(Python)

2024-04-25 05:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为这没有问题,但我真的有这段代码的麻烦,似乎不能想出一个解决办法。你知道吗

我有一本字典,它的键是正名,例如johngreen,我正在使用Sunlight基金会的API来检索国会成员的信息(check here)。现在我需要使用name和lastname进行请求,因此我的代码如下所示:

 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

我猜这和编码有关,但我不知道该怎么解决。你知道吗

不用说,如果我手写一个名字和姓氏,请求就完美地工作了。你知道吗

有人能帮忙吗?谢谢!你知道吗


Tags: key代码inpyjsonmylibline
1条回答
网友
1楼 · 发布于 2024-04-25 05:35:12

这与编码无关。答案根本不是JSON。当我用“John”和“Green”尝试您的代码时,我得到一个400 Bad Request,响应的内容是“不存在这样的对象”。你知道吗

在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

相关问题 更多 >