我得到错误期望值:第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()

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

其他回答

只需检查请求的状态码是否为200。例如:

if status != 200:
    print("An error has occured. [Status code", status, "]")
else:
    data = response.json() #Only convert to Json when status is OK.
    if not data["elements"]:
        print("Empty JSON")
    else:
        "You can extract data here"

在我的情况下,它发生了,因为我读取文件的数据使用file.read(),然后尝试使用json.load(文件)解析它。我通过将json.load(file)替换为json.loads(data)来解决这个问题。

不能工作的代码

with open("text.json") as file:
    data=file.read()
    json_dict=json.load(file)

工作代码

with open("text.json") as file:
   data=file.read()
   json_dict=json.loads(data)

检查文件的编码格式,读取文件时使用相应的编码格式。它会解决你的问题。

with open("AB.json", encoding='utf-8', errors='ignore') as json_data:
     data = json.load(json_data, strict=False)

在我的情况下,这是因为服务器偶尔会给出http错误。所以基本上偶尔我的脚本得到这样的响应,而不是预期的响应:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<h1>502 Bad Gateway</h1>
<p>The proxy server received an invalid response from an upstream server.<hr/>Powered by Tengine</body>
</html>

显然这不是json格式,试图调用.json()将产生JSONDecodeError:期望值:第1行第1列(char 0)

您可以打印导致此错误的确切响应,以便更好地调试。 例如,如果您正在使用请求,那么只需打印.text字段(在调用.json()之前)就可以了。

一定要记得在文件的内容上调用JSON .loads(),而不是JSON的文件路径:

json_file_path = "/path/to/example.json"

with open(json_file_path, 'r') as j:
     contents = json.loads(j.read())

我认为很多人都会时不时地这样做(包括我自己):

contents = json.load(json_file_path)