Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在API调用中使用字典键吗?(Python)_Python_Json_Encoding_Request - Fatal编程技术网

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

我可以在API调用中使用字典键吗?(Python),python,json,encoding,request,Python,Json,Encoding,Request,我认为这没有问题,但我真的有这段代码的问题,似乎无法想出一个解决方案 我有一本字典,它的键值是专有名称,例如John Green,我使用的是阳光基金会的API来检索国会成员的信息()。现在我需要使用name和lastname进行请求,因此我的代码如下所示: for key in my_dict: query_params2 = { 'apikey': 'xxxxxxxxxxx', 'firstname' : key.split()[0],

我认为这没有问题,但我真的有这段代码的问题,似乎无法想出一个解决方案

我有一本字典,它的键值是专有名称,例如John Green,我使用的是阳光基金会的API来检索国会成员的信息()。现在我需要使用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
回溯(最近一次呼叫最后一次):
文件“my_program.py”,第102行,在
data=resp.json()
json格式的文件“//anaconda/lib/python2.7/site packages/requests/models.py”,第741行
返回json.load(self.text,**kwargs)
文件“//anaconda/lib/python2.7/json/_init__.py”,第338行,加载
返回\u默认\u解码器。解码
文件“//anaconda/lib/python2.7/json/decoder.py”,第365行,解码
obj,end=self.raw\u decode(s,idx=\u w(s,0.end())
文件“//anaconda/lib/python2.7/json/decoder.py”,第383行,原始解码
raise VALUERROR(“无法解码JSON对象”)
ValueError:无法解码任何JSON对象
我猜这和编码有关,但我不知道该怎么解决

不用说,如果我手工输入一个名字和姓氏,这个请求就可以完美地工作


有人能帮忙吗?非常感谢

这与编码无关。答案根本不是JSON。当我用“John”和“Green”尝试你的代码时,我得到了一个
400错误请求
,响应的内容是“不存在这样的对象”

在web界面中尝试John Green也会得到一个空的答案。此外,API文档中的URL与示例中的URL不同

以下内容适合我(同样不是约翰·格林):

输出:

检查约翰·格林
0
检查约翰·克里
1.
K000148

也许它适用于某些键,但不适用于其他键。尝试忽略循环中的错误(即,只是
pass
),然后查看最后得到的结果。错误消息是:(1)您的回溯与您的代码不匹配[code has
.decode()
,tb not],以及(2)您没有返回JSON对象。您得到的响应是什么(
resp2
)?
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()