我正在尝试转换json中的响应
response = requests.get('http://solr.library.ucla.edu/solr/sheetmusic/select/?q=%5C*%20AND%20(url_keyword:http*)&version=2.2&start=0&rows=100&indent=on&facet=true&facet.field=r_date_facetRange&wt=json&json.wrf=jsonp1530647389471')
response = json.loads(response.content.decode('utf-8'))
但是我找回了这个错误
~/.virtualenvs/pistache/lib/python3.6/site-packages/requests/models.py in json(self, **kwargs)
890 # used.
891 pass
--> 892 return complexjson.loads(self.text, **kwargs)
893
894 @property
/usr/lib/python3.6/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
352 parse_int is None and parse_float is None and
353 parse_constant is None and object_pairs_hook is None and not kw):
--> 354 return _default_decoder.decode(s)
355 if cls is None:
356 cls = JSONDecoder
/usr/lib/python3.6/json/decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):
/usr/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
答案 0 :(得分:3)
此URL返回的不是JSON,而是JSONP。为了解析响应,您可以从url中删除最后一个参数(json.wrf=jsonp1530647389471
)-然后响应将变为JSON,并且您可以使用json.loads
进行解析。
response = requests.get('http://solr.library.ucla.edu/solr/sheetmusic/select/?q=%5C*%20AND%20(url_keyword:http*)&version=2.2&start=0&rows=100&indent=on&facet=true&facet.field=r_date_facetRange&wt=json')
print json.loads(response.content.decode('utf-8'))
# {u'facet_counts': {u'facet_ranges': {}...
或者,使其更简单:
response = requests.get('http://solr.library.ucla.edu/solr/sheetmusic/select/?q=%5C*%20AND%20(url_keyword:http*)&version=2.2&start=0&rows=100&indent=on&facet=true&facet.field=r_date_facetRange&wt=json').json()
答案 1 :(得分:1)
如果必须使用相同的URL而不对其进行修改,则可以使用re
模块来提取请求的响应内容中的JSON,如下例所示:
import re, json, requests
url = 'http://solr.library.ucla.edu/solr/sheetmusic/select/?q=%5C*%20AND%20(url_keyword:http*)&version=2.2&start=0&rows=100&indent=on&facet=true&facet.field=r_date_facetRange&wt=json&json.wrf=jsonp1530647389471'
resp = requests.get(url)
resp_parsed = re.sub(r'^jsonp\d+\(|\)\s+$', '', resp.text)
data = json.loads(resp_parsed)
print(data)
否则,另一个答案是正确的,并且使用起来更简单。
答案 2 :(得分:0)
我收到解码错误,因为我在循环中读取数据并且连接超时或在几次“获取”后结束我尝试休眠几毫秒以克服此错误
url = "https://api.coindcx.com/exchange/ticker"
while(True):
t.sleep(0.5)
resp = requests.get(url)
resp_parsed = re.sub(r'^jsonp\d+(|)\s+$', '', resp.text)
data = json.loads(resp_parsed)
print(pd.DataFrame(data).query("market=='LINKINR'")['last_price'].values[0])