python JSON feed返回字符串不是对象 [英] python JSON feed returns string not object
本文介绍了python JSON feed返回字符串不是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用以下代码导入此json feed
I can import this json feed with this code
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时,出现以下错误
but when I try to load this JSON feed I get the following error
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
推荐答案
您正尝试加载 JSONP 数据,而不是JSON数据. JSONP(带填充的JSON)将JSON数据包装在回调中.
You are trying to load JSONP data, not JSON data. JSONP (JSON with Padding) wraps the JSON data in a callback.
我找不到同一API的仅JSON版本;您必须先自己解开回调.使用已知长度的简短回调名称可以使自己更轻松:
I could not find a JSON-only version of the same API; you'll have to unwrap the callback yourself first. Use a short callback name of known length to make this easier for yourself:
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(...);
回调代码.
The string slice removes the c(...);
callback code from the start and end of the response.
这篇关于python JSON feed返回字符串不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文