ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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

错误发生在 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)
为什么要解码响应? (simple)json 可以很好地处理 UTF-8 编码的 JSON。
最后但同样重要的是,print repr(response_json) 告诉您什么正在传递给 .loads()
还有一个:当您可以使用标准库 json(与 simplejson 相同的库)时,为什么还要使用 simplejson
当我执行 print repr(response_json) 时,它只会显示 u''
那是一个空字符串。您的 web_fetch() 呼叫失败。

M
Martijn Pieters

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

笔记:

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

无需将响应从 UTF8 解码为 unicode,simplejson / json .loads() 方法可以原生处理 UTF8 编码数据。

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

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

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,并采取良好措施捕获异常:

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

这对于确定 json 何时存在或使用作为替代响应的 response.text 很有用。
a
alex

请务必记住对文件的 contents 调用 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.loads(json_file_path)

我认为在这种情况下应该使用 json.load()
感谢这个精彩的答案,这救了我!
我两年前发布了这个答案,但我刚才犯了同样的错误:(
json.load() 的问题是,如果文件为空,那么您将收到与问题相同的错误。如果从 HTTP 响应中加载 json 内容,可以通过 HTTP 状态码进行检查,但如果从文件中加载,则需要检查文件是否为空。所以最好使用 j.read() 然后检查它是否为空。
L
Lorenz Lo Sauer

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

在大多数情况下,您的 json.loads- JSONDecodeError: Expecting value: line 1 column 1 (char 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()

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


在评论中,很明显 OP 得到了一个空洞的回应。由于 requests.get(url).json() Just Works,JSON 也没有格式错误。
JSONDecodeError: Expecting value: line 1 column 1 (char 0) 特别是在将空字符串传递给 json decode 时发生
JSONDecodeError: Expecting value: line 1 column 1 (char 0) 也会在 json 响应中的第一行无效时发生。运行 az cli 命令的示例响应是 ["WARNING: The default kind for created storage account will change to 'StorageV2' from 'Storage' in the future", '{',。这给了我导致我来到这里的错误。响应的其余部分是一个有效的 json 对象。只是第一行就打破了一切。
在某些情况下,需要将标头作为 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } 与请求 URL 一起传递,以便接收有效的 JSON 响应。
C
Christophe Roussy

当您有类似 404 的 http 错误代码并尝试将响应解析为 JSON 时,使用 requestsJSONDecodeError 可能会发生!

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

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


很抱歉旧评论,但你能链接到一个例子吗?我正在尝试将我的技能从“执行动作”转变为“尝试执行动作,返回响应,做出相应的反应”。
@dcclassics:示例:它在服务器端失败,服务器通过显示错误页面 (HTML) 而不是使用 JSON 进行响应,因此解析答案的代码将尝试读取 JSON,但会在 HTML 标签上失败。
服务器可以并且确实在错误响应中包含 JSON 主体。这不仅仅是 200 个 OK 响应。您要检查 Content-Type 标头。
T
The Godfather

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

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

通过 encoding='utf-8' 的微小变化,这对我有用,所以我想有时您需要尝试一些事情。
不能同意更多,这真的取决于设置......
G
Galuoises

我在尝试读取 json 文件时遇到了同样的问题

json.loads("file.json")

我解决了这个问题

with open("file.json", "r") as read_file:
   data = json.load(read_file)

也许这可以帮助你的情况


我认为确保必须检查 FILE PATH 很重要。
C
Community

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

>>> 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 = {}

在我的代码中进一步调试时,我调用了 response.read(),然后当另一个调用导致 Expecting value: line 1 等时感到沮丧。删除了调试语句并解决了问题。
要调试,您还可以使用这个不错的网站jsonlint.com
它也可以是一个以 b 开头的空二进制字符串。如果您使用 if 来检测它,那就不一样了:b''
u
user9571515

我遇到了同样的问题,在打印从 json 文件打开的 json 字符串时,发现 json 字符串以 '' 开头,通过做一些研究是由于文件默认使用 UTF-8 解码,并且通过将编码更改为 utf-8-sig,标记被剥离并加载 json 没问题:

open('test.json', encoding='utf-8-sig')

解决了我的问题。与您的描述几乎相同,开头有一些奇怪的字符串。非常感谢。
b
bryan

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

import json
struct = {}
try:
    response_json = response_json.decode('utf-8').replace('\0', '')
    struct = json.loads(response_json)
except:
    print('bad json: ', response_json)
return struct

response_json 未定义
原始海报将响应 json 称为 response_json 。
W
Wout VC

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

S
Solano Pillaca Jason Ennio

我有同样的问题,在我的情况下,我解决了这样的问题:

import json

with open("migrate.json", "rb") as read_file:
   data = json.load(read_file)

A
Aditya Rajgor

这是我想在 python 中加载 json 文件时找到的极简解决方案

import json
data = json.load(open('file_name.json'))

如果这给出错误说字符在位置 X 和 Y 上不匹配,那么只需在 open 圆括号内添加 encoding='utf-8'

data = json.load(open('file_name.json', encoding='utf-8'))

说明 open 打开文件并读取随后在 json.load 中解析的内容。

请注意,使用 with open() as f 比上述语法更可靠,因为它确保文件在执行后关闭,完整的语法将是

with open('file_name.json') as f:
    data = json.load(f)

K
Kelsie C

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

为了调试,我使用了:

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

我从 API 收到了 404 响应。


它可以简化为 response.status_codeprint(response.status_code)
相同的。我收到 403 错误。所以我的回复看起来像这样,<Response [403]> 这不是有效的 json 格式
S
Seu Madruga

我对请求(python库)有同样的问题。它恰好是 accept-encoding 标头。

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

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


A
Ashish Sharma

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


N
Neel0507

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


F
FastGTR

对我来说,它是服务器以 200 以外的内容响应,并且响应不是 json 格式的。我最终在 json 解析之前这样做了:

# this is the https request for data in json format
response_json = requests.get() 

# only proceed if I have a 200 response which is saved in status_code
if (response_json.status_code == 200):  
     response = response_json.json() #converting from json to dictionary using json library

这对我来说是个问题。状态码是 500(内部服务器错误)而不是 200,因此没有返回 json,因此 json 的第 1 列第 1 行中没有任何内容。检查请求状态代码是否符合您的预期总是很好。
t
ti7

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

request data arg 上使用 json.dumps() 创建正确转义的 JSON 字符串,然后再 POST 为我解决了这个问题

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

Q
Qin Heyang

在我的情况下,这是因为服务器偶尔会给出 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: Expecting value: line 1 column 1 (char 0)

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


p
parsecer

我做了:

打开 test.txt 文件,写入数据 打开 test.txt 文件,读取数据

所以我没有在 1 之后关闭文件。

我添加了

outfile.close()

现在它可以工作了


我也有使用两个 with 语句的类似问题,即使它应该自己处理关闭
d
drorhun

如果您是 Windows 用户,Tweepy API 可以在数据对象之间生成一个空行。由于这种情况,您会收到“JSONDecodeError: Expecting value: line 1 column 1 (char 0)”错误。为避免此错误,您可以删除空行。

例如:

 def on_data(self, data):
        try:
            with open('sentiment.json', 'a', newline='\n') as f:
                f.write(data)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

参考:Twitter stream API gives JSONDecodeError("Expecting value", s, err.value) from None


我不认为空行是一个问题。它清楚地指出错误位于第 1 行第 1 列。我认为这种解决方法有效,因为它正在从文件中删除 BOM。您可以快速验证: 1. 检查您的原始文件的大小(右键单击>属性),它可以是 134.859 字节 2. 使用 Notepad++ 打开原始文件 3. 将编码从“UTF-8-BOM”更改为“ UTF-8”。保存 4. 再次检查大小。它可以是 134.856(少 3 个字节)
L
Learning from masters

如果您使用标头并且 "Accept-Encoding": "gzip, deflate, br" 使用 pip install 安装 brotli 库。您不需要将 brotli 导入到您的 py 文件中。


s
suraj

就我而言,这是用双引号替换单引号的简单解决方案。你可以找到我的答案here


虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。
T
Thenujan Sandramohan

在我的情况下,它发生是因为我使用 file.read() 读取文件的数据,然后尝试使用 json.load(file) 解析它。我通过将 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)

您的 file 变量是 docs.python.org/3/library/json.html#basic-usage 中描述的 fp,所以像这样使用它:json.load(file)
@杰西H。这不是我在无效代码部分所做的吗?它抛出错误
它不起作用的原因是您在 file 上使用了 .read() 方法。在此处阅读更多相关信息:stackoverflow.com/a/3906148/12678216。您应该删除该行,看看它是否有效。
@杰西H。是的,我已经意识到 .read() 方法导致了这个问题,所以我在答案中提出了一种解决方法。为什么你认为这是一个糟糕的答案?

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅