尝试解码 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()
呼叫失败。
您的代码产生了一个空的响应主体,您需要检查它或捕获引发的异常。服务器可能以 204 No Content 响应进行响应,或者返回了非 200 范围的状态代码(404 Not Found 等)。检查这个。
笔记:
无需使用 simplejson 库,Python 中包含与 json 模块相同的库。
无需将响应从 UTF8 解码为 unicode,simplejson / json .loads() 方法可以原生处理 UTF8 编码数据。
pycurl 有一个非常古老的 API。除非您对使用它有特定要求,否则会有更好的选择。
requests
或 httpx
都提供了更友好的 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
请务必记住对文件的 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()
然后检查它是否为空。
检查响应数据主体,是否存在实际数据以及数据转储是否格式正确。
在大多数情况下,您的 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()
注意:数据中的引号必须正确转义
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 响应。
当您有类似 404 的 http 错误代码并尝试将响应解析为 JSON 时,使用 requests
库 JSONDecodeError
可能会发生!
您必须首先检查 200 (OK) 或让它在错误时引发以避免这种情况。我希望它以不那么神秘的错误消息而失败。
注意:正如 Martijn Pieters 在评论服务器中所述,可以在出现错误时使用 JSON 响应(这取决于实现),因此检查 Content-Type
标头更可靠.
检查文件的编码格式并在读取文件时使用相应的编码格式。它会解决你的问题。
with open("AB.json", encoding='utf-8', errors='ignore') as json_data:
data = json.load(json_data, strict=False)
encoding='utf-8'
的微小变化,这对我有用,所以我想有时您需要尝试一些事情。
我在尝试读取 json 文件时遇到了同样的问题
json.loads("file.json")
我解决了这个问题
with open("file.json", "r") as read_file:
data = json.load(read_file)
也许这可以帮助你的情况
很多时候,这将是因为您尝试解析的字符串是空白的:
>>> 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
等时感到沮丧。删除了调试语句并解决了问题。
我遇到了同样的问题,在打印从 json 文件打开的 json 字符串时,发现 json 字符串以 '' 开头,通过做一些研究是由于文件默认使用 UTF-8 解码,并且通过将编码更改为 utf-8-sig,标记被剥离并加载 json 没问题:
open('test.json', encoding='utf-8-sig')
即使在调用 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
只需检查请求是否有状态码 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"
我有同样的问题,在我的情况下,我解决了这样的问题:
import json
with open("migrate.json", "rb") as read_file:
data = json.load(read_file)
这是我想在 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)
我在使用请求时遇到了这个问题。感谢 Christophe Roussy 的解释。
为了调试,我使用了:
response = requests.get(url)
logger.info(type(response))
我从 API 收到了 404 响应。
response.status_code
或 print(response.status_code)
。
<Response [403]>
这不是有效的 json 格式
我对请求(python库)有同样的问题。它恰好是 accept-encoding
标头。
它是这样设置的:'accept-encoding': 'gzip, deflate, br'
我只是将它从请求中删除并停止收到错误。
在我的情况下,我在 if 和 else 块中执行了两次 file.read() ,这导致了这个错误。所以请确保不要犯这个错误,并在变量中保存包含并多次使用变量。
对我来说,它没有在请求中使用身份验证。
对我来说,它是服务器以 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
我在基于 Python 的 Web API 的响应 .text
中收到了这样一个错误,但它把我带到了这里,所以这可能会帮助其他有类似问题的人(使用 requests
时很难在搜索中过滤响应和请求问题..)
在 request data
arg 上使用 json.dumps()
创建正确转义的 JSON 字符串,然后再 POST 为我解决了这个问题
requests.post(url, data=json.dumps(data))
在我的情况下,这是因为服务器偶尔会给出 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()
之前)就可以了。
我做了:
打开 test.txt 文件,写入数据 打开 test.txt 文件,读取数据
所以我没有在 1 之后关闭文件。
我添加了
outfile.close()
现在它可以工作了
如果您是 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
如果您使用标头并且 "Accept-Encoding": "gzip, deflate, br"
使用 pip install 安装 brotli 库。您不需要将 brotli 导入到您的 py 文件中。
在我的情况下,它发生是因为我使用 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)
.read()
方法导致了这个问题,所以我在答案中提出了一种解决方法。为什么你认为这是一个糟糕的答案?
不定期副业成功案例分享
json
何时存在或使用作为替代响应的response.text
很有用。