ValueError:无法解码JSON对象,respobj.json()失败

时间:2014-12-29 18:29:21

标签: python json linkedin python-requests

所以基本上我的代码试图根据Linkedin API获取共享计数,然后将其放在一个单独的google spreadsheat文件中,所有其他功能都正常工作,这个我得到标题中提到的错误,这是代码,问题似乎在第40行。

1   def Func1():
2     return "Out from Function One"
3   
4   def Func2(param1, param2='', status='Okay'):
5     return "%s %s" % (param1, param2)
6   
7   def tweets(url):
8     import requests
9     api = "http://urls.api.twitter.com/1/urls/count.json?url="
10    respobj = requests.get(api + url)
11    adict = respobj.json()
12    return adict["count"]
13  
14  def plusses(url):
15    import requests
16    api = "https://clients6.google.com/rpc"
17    jobj = '''{
18      "method":"pos.plusones.get",
19      "id":"p",
20      "params":{
21          "nolog":true,
22          "id":"%s",
23          "source":"widget",
24          "userId":"@viewer",
25          "groupId":"@self"
26          },
27      "jsonrpc":"2.0",
28      "key":"p",
29      "apiVersion":"v1"
30    }''' % (url)
31    respobj = requests.post(api, jobj)
32    adict = respobj.json()
33    return adict['result']['metadata']['globalCounts']['count']
34  
35  
36  def linked(url):
37    import requests
38    api = "http://www.linkedin.com/countserv/count/share?url="
39    respobj = requests.get(api + url)
40    adict = respobj.json()
41    return adict

1 个答案:

答案 0 :(得分:2)

http://www.linkedin.com/countserv/count/share?url=端点不会返回可通过json模块直接加载的内容(请参阅JSONP):

>>> import requests
>>> url = 'https://www.linkedin.com/countserv/count/share?url=test'
>>> response = requests.get(url)
>>> response.headers['Content-Type']
'text/javascript;charset=UTF-8'
>>> response.content
'IN.Tags.Share.handleCount({"count":446,"fCnt":"446","fCntPlusOne":"447","url":"test"});'

您可以做的是提供callback并从响应中提取json部分:

>>> import json
>>> import requests
>>>
>>> url = 'test'
>>> callback = 'test'
>>> url = 'https://www.linkedin.com/countserv/count/share?url={url}&lang=en_US&callback={callback}'.format(url=url, callback=callback)
>>> response = requests.get(url)
>>> json.loads(response.content[len(callback)+1:-2])
{u'count': 446, u'url': u'test', u'fCntPlusOne': u'447', u'fCnt': u'446'}