Expecting value: line 1 column 1 (char 0)尝试解码JSON 时出现错误。
Expecting value: line 1 column 1 (char 0)
我用于API调用的URL在浏览器中可以正常工作,但是通过curl请求完成时会出现此错误。以下是我用于curl请求的代码。
错误发生在 return simplejson.loads(response_json)
return simplejson.loads(response_json)
response_json = self.web_fetch(url) response_json = response_json.decode('utf-8') return json.loads(response_json) def web_fetch(self, url): buffer = StringIO() curl = pycurl.Curl() curl.setopt(curl.URL, url) curl.setopt(curl.TIMEOUT, self.timeout) curl.setopt(curl.WRITEFUNCTION, buffer.write) curl.perform() curl.close() response = buffer.getvalue().strip() return response
完整回溯:
追溯:
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/Users/nab/Desktop/pricestore/pricemodels/views.py" in view_category 620. apicall=api.API().search_parts(category_id= str(categoryofpart.api_id), manufacturer = manufacturer, filter = filters, start=(catpage-1)*20, limit=20, sort_by='[["mpn","asc"]]') File "/Users/nab/Desktop/pricestore/pricemodels/api.py" in search_parts 176. return simplejson.loads(response_json) File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/__init__.py" in loads 455. return _default_decoder.decode(s) File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in decode 374. obj, end = self.raw_decode(s) File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in raw_decode 393. return self.scan_once(s, idx=_w(s, idx).end()) Exception Type: JSONDecodeError at /pricemodels/2/dir/ Exception Value: Expecting value: line 1 column 1 (char 0)
总结评论中的对话:
不需要使用simplejson库,Python作为json模块包含了相同的库。
simplejson
json
无需解码从UTF8到unicode的响应,simplejson/ json .loads()方法可以本地处理UTF8编码的数据。
.loads()
pycurl有一个非常古老的API。除非您有特定的使用要求,否则会有更好的选择。
pycurl
requests提供最友好的API,包括JSON支持。如果可以,将您的通话替换为:
requests
import requests return requests.get(url).json()