JSONDecodeError:预期值:第 1 行第 1 列(字符 0)
- 2024-12-05 08:37:00
- admin 原创
- 153
问题描述:
Expecting value: line 1 column 1 (char 0)
尝试解码 JSON 时出现错误。
我用于 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)
解决方案 1:
您的代码生成了一个空的响应主体;您需要检查该主体或捕获引发的异常。服务器可能以 204 No Content 响应进行响应,或者返回非 200 范围的状态代码(404 Not Found 等)。请检查这一点。
笔记:
无需使用
simplejson
库,Python 中包含与json
模块相同的库。(本说明引用了问题的原始表述)。无需将响应从 UTF8 解码为 Unicode,
simplejson
/json
.loads()
方法可以原生处理 UTF8 编码的数据。pycurl
有一个非常古老的 API。除非你有使用它的特定要求,否则还有更好的选择。
或者requests
提供httpx
更友好的 API,包括 JSON 支持。
使用 Requests 包的示例
如果可以的话,请将您的呼叫替换为:
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
解决方案 2:
请务必记住调用文件的内容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)
解决方案 3:
检查响应数据体,是否存在实际数据以及数据转储是否格式正确。
在大多数情况下,您的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()
注意:数据中的引号必须正确转义
解决方案 4:
当您遇到 http 错误代码(例如 404)并尝试将响应解析为 JSON 时,可能会发生此requests
情况!JSONDecodeError
您必须先检查 200(OK)或让它在出现错误时引发以避免这种情况。我希望它失败时出现一个不那么神秘的错误消息。
注意:正如 Martijn Pieters 在评论中所述,服务器可以在出现错误时使用 JSON 进行响应(这取决于实现),因此检查Content-Type
标头更可靠。
解决方案 5:
检查文件的编码格式,并在读取文件时使用相应的编码格式。这将解决您的问题。
with open("AB.json", encoding='utf-8', errors='ignore') as json_data:
data = json.load(json_data, strict=False)
解决方案 6:
我在尝试读取 json 文件时遇到了同样的问题
json.loads("file.json")
我解决了这个问题
with open("file.json", "r") as read_file:
data = json.load(read_file)
也许这可以帮助你
解决方案 7:
我遇到了同样的问题,在打印出从 json 文件打开的 json 字符串时,发现 json 字符串以 '' 开头,经过一番研究,这是因为该文件默认使用 UTF-8 解码,通过将编码更改为 utf-8-sig,标记被删除并且加载 json 没有问题:
open('test.json', encoding='utf-8-sig')
解决方案 8:
很多时候,这是因为您尝试解析的字符串是空的:
>>> 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 = {}
解决方案 9:
这是我在 python 中加载 json 文件时找到的最简单的解决方案
import json
data = json.load(open('file_name.json'))
如果出现错误,指出字符在位置 X 和 Y 不匹配,则只需在圆括号encoding='utf-8'
内添加open
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)
解决方案 10:
我遇到了同样的问题,就我而言,我是这么解决的:
import json
with open("migrate.json", "rb") as read_file:
data = json.load(read_file)
解决方案 11:
即使在调用了解码()之后,也可能会有嵌入的 0。使用 replace():
import json
struct = {}
try:
response_json = response_json.decode('utf-8').replace(' ', '')
struct = json.loads(response_json)
except:
print('bad json: ', response_json)
return struct
解决方案 12:
我在使用请求时确实遇到了这个问题。感谢 Christophe Roussy 的解释。
为了调试,我使用了:
response = requests.get(url)
logger.info(type(response))
我从 API 获得了 404 响应。
解决方案 13:
我在使用请求(python 库)时遇到了同样的问题。它恰好是标题accept-encoding
。
设置如下:'accept-encoding': 'gzip, deflate, br'
我只是将其从请求中删除并不再出现错误。
解决方案 14:
只需检查请求是否有状态代码 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"
解决方案 15:
就我而言,我在 if 和 else 块中执行了两次 file.read(),这导致了此错误。因此,请确保不要犯此错误并将 contain 保存在变量中并多次使用变量。
解决方案 16:
在我的情况下,发生这种情况是因为我使用读取了文件的数据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)
解决方案 17:
对我来说,它没有在请求中使用身份验证。
解决方案 18:
我做到了:
打开
test.txt
文件,写入数据打开
test.txt
文件,读取数据
所以我在1之后没有关闭文件。
我补充道
outfile.close()
现在它起作用了
解决方案 19:
对我来说,服务器响应的不是 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
解决方案 20:
我在基于 Python 的 Web API 的响应中收到了这样的错误.text
,但它将我引导到这里,因此这可能会对遇到类似问题的人有所帮助(在使用时在搜索中过滤响应和请求问题非常困难requests
..)
在 POST 之前使用json.dumps()
请求参数 data
创建正确转义的 JSON 字符串解决了这个问题
requests.post(url, data=json.dumps(data))
解决方案 21:
就我的情况而言,这是因为服务器偶尔会给出 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()
)即可。
解决方案 22:
对我来说,最终的解决方案是在编码设置中。
我的 json 有效,但编码稍有不同(UTF-8 带 BOM),导致同样的错误。因此我指定了编码如下:
with open(file, encoding="utf_8_sig") as j_file:
json_file = json.load(j_file)
检查确切的编码(例如使用写字板)并调整编码设置可能会有所帮助。
解决方案 23:
如果您是 Windows 用户,Tweepy API 可能会在数据对象之间生成一个空行。由于这种情况,您可能会收到“JSONDecodeError:Expecting value:line 1 column 1 (char 0)”错误。要避免此错误,您可以删除空行。
例如:
def on_data(self, data):
try:
with open('sentiment.json', 'a', newline='
') as f:
f.write(data)
return True
except BaseException as e:
print("Error on_data: %s" % str(e))
return True
参考:
Twitter stream API 从 None 给出 JSONDecodeError(“Expecting value”, s, err.value)
解决方案 24:
如果您使用标题并且已"Accept-Encoding": "gzip, deflate, br"
使用 pip install 安装了 brotli 库。 您无需将 brotli 导入到您的 py 文件中。
解决方案 25:
当向 API 端点发出HTTPHEAD
方法请求时,也会出现同样的问题,例如,该方法通常会在请求的响应主体中使用 JSON 数据进行响应GET
(类似于此答案HEAD
中演示的 FastAPI 后端)。 但是,对方法的响应通常没有主体。
因此,当尝试在json()
响应上调用该方法时,如下所示:
import requests
url = 'http://127.0.0.1:8000/'
r = requests.head(url) # perform a HEAD request
print(r.status_code)
print(r.json()) # attempting to read an empty response body as JSON would raise an exception
将引发以下异常:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
...在处理上述异常时,发生了另一个异常:
requests.exceptions.JSONDecodeError: [Errno Expecting value] : 0
因此,在执行请求时,请确保在调用方法HEAD
之前响应中有主体(通常没有) 。您可以改用,它将以字节形式打印出响应内容,或者简单地(如果响应主体为空)。r.json()
`print(r.content)`b''
解决方案 26:
在 Python 3.9 上,我使用了这个:
with open("intents.json") as file:
data=file.read()
json_dict=json.dumps(data)```
解决方案 27:
有时,这种情况可能是由于 JSON 语法错误而发生的。对我来说,当花括号末尾有尾随逗号时就会发生这种情况。如果你有一些带有 Intellisense 的 JSON 解析 IDE,比如 VSCode,你可以轻松找出所有的语法错误。
扫码咨询,免费领取项目管理大礼包!