我得到错误期望值:第1行第1列(字符0)时试图解码JSON。

我用于API调用的URL在浏览器中工作正常,但在通过curl请求完成时给出了这个错误。下面是我用于curl请求的代码。

错误发生在返回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)

当前回答

对我来说,它没有在请求中使用身份验证。

其他回答

检查响应数据体,是否有实际数据,数据转储格式是否正确。

在大多数情况下,你的json。JSONDecodeError:期望值:第1行第1列(字符0)错误是由于:

非json格式引用 XML/HTML输出(即以<开头的字符串),或 不兼容的字符编码

最终,该错误告诉您,在第一个位置,字符串已经不符合JSON。

因此,如果解析失败,尽管有一个乍一看像JSON的数据体,尝试替换数据体的引号:

import sys, json
struct = {}
try:
  try: #try parsing to dict
    dataform = str(response_json).strip("'<>() ").replace('\'', '\"')
    struct = json.loads(dataform)
  except:
    print repr(resonse_json)
    print sys.exc_info()

注意:数据中的引号必须正确转义

在请求库中,当你遇到404这样的http错误代码并试图将响应解析为JSON时,JSONDecodeError就会发生!

您必须首先检查200 (OK)或让它在错误时抛出以避免这种情况。 我希望它失败时没有那么神秘的错误信息。

注意:正如Martijn Pieters在评论中所说,服务器可以在出现错误时使用JSON进行响应(这取决于实现),因此检查Content-Type报头更可靠。

很多时候,这是因为你试图解析的字符串是空的:

>>> import json
>>> x = json.loads("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

你可以通过事先检查json_string是否为空来补救:

import json

if json_string:
    x = json.loads(json_string)
else:
    # Your code/logic here 
    x = {}

在我的例子中,我在if和else块中执行了两次file.read(),这导致了这个错误。所以请确保不要犯这个错误并在变量中保留contains并多次使用变量。

我在使用请求时就遇到了这个问题。 感谢Christophe Roussy的解释。

为了调试,我使用:

response = requests.get(url)
logger.info(type(response))

我从API得到一个404响应。