Python JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16573332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:03:17  来源:igfitidea点击:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

pythonjsonapicurl

提问by user1328021

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

Expecting value: line 1 column 1 (char 0)尝试解码 JSON时出现错误。

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.

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

The error happens at 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

Full Traceback:

完整追溯:

Traceback:

追溯:

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)

采纳答案by Martijn Pieters

To summarize the conversation in the comments:

在评论中总结对话:

  • There is no need to use simplejsonlibrary, the same library is included with Python as the jsonmodule.

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

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

  • 无需使用simplejson库,Python 中包含与json模块相同的库。

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

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

requestsoffers the most friendly API, including JSON support. If you can, replace your call with:

requests提供最友好的 API,包括 JSON 支持。如果可以,请将您的电话替换为:

import requests

return requests.get(url).json()

回答by Lorenz Lo Sauer

Check the response data-body, whether actual data is present and a data-dump appears to be well-formatted.

检查响应数据主体,是否存在实际数据以及数据转储是否格式正确。

In most cases your json.loads- JSONDecodeError: Expecting value: line 1 column 1 (char 0)error is due to :

在大多数情况下,您的json.loads-JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误是由于:

  • non-JSON conforming quoting
  • XML/HTML output (that is, a string starting with <), or
  • incompatible character encoding
  • 不符合 JSON 的引用
  • XML/HTML 输出(即以 < 开头的字符串),或
  • 不兼容的字符编码

Ultimately the error tells you that at the very first position the string already doesn't conform to JSON.

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

As such, if parsing fails despite having a data-body that looks JSON likeat first glance, try replacing the quotes of the data-body:

因此,如果尽管数据主体乍一看看起来像 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()

Note: Quotes within the data must be properly escaped

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

回答by Christophe Roussy

With the requestslib JSONDecodeErrorcan happen when you have an http error code like 404 and try to parse the response as JSON !

当您有像 404 这样的 http 错误代码并尝试将响应解析为 JSON 时,可能会使用requestslib JSONDecodeError

You must first check for 200 (OK) or let it raise on error to avoid this case. I wish it failed with a less cryptic error message.

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

NOTE: as Martijn Pieters stated in the comments servers canrespond with JSON in case of errors (it depends on the implementation), so checking the Content-Typeheader is more reliable.

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

回答by bryan

There may be embedded 0's, even after calling decode(). Use replace():

即使在调用 decode() 之后,也可能会嵌入 0。使用替换():

import json
struct = {}
try:
    response_json = response_json.decode('utf-8').replace('
response = requests.get(url)
logger.info(type(response))
', '') struct = json.loads(response_json) except: print('bad json: ', response_json) return struct

回答by Kelsie Braidwood

I had exactly this issue using requests. Thanks to Christophe Roussy for his explanation.

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

To debug, I used:

为了调试,我使用了:

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

I was getting a 404 response back from the API.

我从 API 收到了 404 响应。

回答by Seu Madruga

I was having the same problem with requests (the python library). It happened to be the accept-encodingheader.

我在请求(python 库)方面遇到了同样的问题。它恰好是accept-encoding标题。

It was set this way: 'accept-encoding': 'gzip, deflate, br'

它是这样设置的: 'accept-encoding': 'gzip, deflate, br'

I simply removed it from the request and stopped getting the error.

我只是从请求中删除它并停止收到错误。

回答by Ramineni Ravi Teja

check encoding format of your file and use corresponding encoding format while reading file. It will solve your problem.

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

>>> 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)

回答by Alex W

A lot of times, this will be because the string you're trying to parse is blank:

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

import json

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

You can remedy by checking whether json_stringis empty beforehand:

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

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

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

回答by alex

I think it's worth mentioning that in cases where you're parsing the contents of a JSON file itself - sanity checks can be useful to ensure that you're actually invoking json.loads()on the contentsof the file, as opposed to the file pathof that JSON:

我认为值得一提的是,在您解析 JSON 文件本身的内容的情况下 - 健全性检查可用于确保您实际调用文件json.loads()内容,而不是该 JSON的文件路径

contents = json.loads(json_file_path)

I'm a little embarrassed to admit that this can happen sometimes:

我有点尴尬地承认这有时会发生:

##代码##

回答by Neel0507

For me, it was not using authentication in the request.

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