JSONDecodeError:期望值:第 1 行第 1 列(字符 0) [英] JSONDecodeError: Expecting value: line 1 column 1 (char 0)

查看:55
本文介绍了JSONDecodeError:期望值:第 1 行第 1 列(字符 0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试解码 JSON 时遇到错误 Expecting value: line 1 column 1 (char 0).

I am getting error Expecting value: line 1 column 1 (char 0) when trying to decode JSON.

我用于 API 调用的 URL 在浏览器中工作正常,但在通过 curl 请求完成时会出现此错误.以下是我用于 curl 请求的代码.

The URL I use for the API call works fine in the browser, but gives this error when done through a curl request. The following is the code I use for the curl request.

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

推荐答案

您的代码生成了一个空的响应主体,您需要检查它或捕获引发的异常.服务器可能以 204 No Content 响应进行响应,或者返回了非 200 范围的状态代码(404 Not Found 等).检查这个.

Your code produced an empty response body, you'd want to check for that or catch the exception raised. It is possible the server responded with a 204 No Content response, or a non-200-range status code was returned (404 Not Found, etc.). Check for this.

注意:

  • 不需要使用 simplejson 库,Python 中包含与 json 模块相同的库.

  • There is no need to use simplejson library, the same library is included with Python as the json module.

不需要将响应从 UTF8 解码为 un​​icode,simplejson/json .loads() 方法可以原生处理 UTF8 编码数据.

There is no need to decode a response from UTF8 to unicode, the simplejson / json .loads() method can handle UTF8 encoded data natively.

pycurl 有一个非常古老的 API.除非您有使用它的特定要求,否则有更好的选择.

pycurl has a very archaic API. Unless you have a specific requirement for using it, there are better choices.

requestshttpx 提供了更友好的 API,包括 JSON 支持.如果可以,请将您的电话替换为:

Either the requests or httpx offers much friendlier APIs, including JSON support. If you can, replace your call with:

import requests

response = requests.get(url)
response.raise_for_status()  # raises exception when not a 2xx response
if response.status_code != 204:
    return response.json()

当然,这不会保护您免受不符合 HTTP 标准的 URL 的侵害;在可能的情况下使用任意 URL 时,请检查服务器是否打算通过检查 Content-Type 标头为您提供 JSON,并作为良好的措施捕获异常:

Of course, this won't protect you from a URL that doesn't comply with HTTP standards; when using arbirary URLs where this is a possibility, check if the server intended to give you JSON by checking the Content-Type header, and for good measure catch the exception:

if (
    response.status_code != 204 and
    response.headers["content-type"].strip().startswith("application/json")
):
    try:
        return response.json()
    except ValueError:
        # decide how to handle a server that's misbehaving to this extent

这篇关于JSONDecodeError:期望值:第 1 行第 1 列(字符 0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆