gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:02:18 24 4
gpt4 key购买 nike

我可以使用此代码导入此 json feed

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

最佳答案

您正在尝试加载 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(...); 回调代码。

关于python JSON feed 返回字符串而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com