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

其他回答

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

为了调试,我使用:

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

我从API得到一个404响应。

在我的情况下,它发生了,因为我读取文件的数据使用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)

我在一个基于python的web API的响应.text中收到了这样一个错误,但它把我带到了这里,所以这可能会帮助其他人解决类似的问题(在使用请求时,很难在搜索中过滤响应和请求问题..)

在请求数据arg上使用JSON .dumps()创建一个正确转义的JSON字符串,然后再发布,为我修复了这个问题

requests.post(url, data=json.dumps(data))

只需检查请求的状态码是否为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"

一定要记得在文件的内容上调用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)