python JSON feed返回字符串而不是对象

时间:2014-09-13 23:09:46

标签: python json

我可以使用此代码导入此json供稿

import json
import requests
url = 'http://espn.go.com/sports/scores/feed?sportId=28&eventId=0&rand=1410039271798&xhr=1'
r = requests.get(url)
pbpObj = json.loads(r.content)

但是当我尝试加载此JSON Feed时,我收到以下错误

'http://data.ncaa.com/jsonp/scoreboard/football/fbs/2014/03/scoreboard.html?callback=ncaaScoreboard.dispScoreboard'

    ValueError                                Traceback (most recent call last)
<ipython-input-499-a086c9c2c95f> in <module>()
      3 url = 'http://data.ncaa.com/jsonp/scoreboard/football/fbs/2014/03/scoreboard.html?callback=ncaaScoreboard.dispScoreboard'
      4 r = requests.get(url)
----> 5 pbpObj = json.loads(r.content)

C:\Python27\lib\json\__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    336             parse_int is None and parse_float is None and
    337             parse_constant is None and object_pairs_hook is None and not kw):
--> 338         return _default_decoder.decode(s)
    339     if cls is None:
    340         cls = JSONDecoder

C:\Python27\lib\json\decoder.pyc in decode(self, s, _w)
    363 
    364         """
--> 365         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    366         end = _w(s, end).end()
    367         if end != len(s):

C:\Python27\lib\json\decoder.pyc in raw_decode(self, s, idx)
    381             obj, end = self.scan_once(s, idx)
    382         except StopIteration:
--> 383             raise ValueError("No JSON object could be decoded")
    384         return obj, end

ValueError: No JSON object could be decoded

1 个答案:

答案 0 :(得分:2)

您正在尝试加载 JSONP 数据,而不是JSON数据。 JSONP (JSON with Padding)将JSON数据包装在回调中。

我找不到同一API的JSON版本;你必须先自己解开回调。使用已知长度的简短回调名称可以让您更轻松:

url = 'http://data.ncaa.com/jsonp/scoreboard/football/fbs/2014/03/scoreboard.html?callback=c'
r = requests.get(url)
pbpObj = json.loads(r.content[2:-2])

字符串切片从响应的开头和结尾删除c(...);回调代码。