![](/img/trans.png)
[英]JSONDecodeError: Expecting value: line 1 column 1 (char 0) in python
[英]JSONDecodeError: Expecting value: line 1 column 1 (char 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)
您的代碼生成了一個空的響應主體,您需要檢查它或捕獲引發的異常。 服務器可能以 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
請務必記住對文件的內容調用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.loads
- JSONDecodeError: Expecting value: line 1 column 1 (char 0)
錯誤是由於:
最終,錯誤告訴您,在第一個位置,字符串已經不符合 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
庫JSONDecodeError
當您有一個像 404 這樣的 http 錯誤代碼並嘗試將響應解析為 JSON 時可能會發生!
您必須首先檢查 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)
我在嘗試讀取 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 = {}
我遇到了同樣的問題,在打印出從 json 文件打開的 json 字符串時,發現 json 字符串以 '' 開頭,這是因為文件默認使用 UTF-8 解碼,並且通過將編碼更改為 utf-8-sig,標記將被剝離並加載 json 沒問題:
open('test.json', encoding='utf-8-sig')
我收到此錯誤是因為我的 json 文件為空。
即使在調用 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
我遇到了同樣的問題,就我而言,我是這樣解決的:
import json
with open("migrate.json", "rb") as read_file:
data = json.load(read_file)
我在使用請求時遇到了這個問題。 感謝 Christophe Roussy 的解釋。
為了調試,我使用了:
response = requests.get(url)
logger.info(type(response))
我從 API 收到了 404 響應。
只需檢查請求是否具有狀態代碼 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"
我在請求(python 庫)方面遇到了同樣的問題。 它恰好是accept-encoding
標頭。
它是這樣設置的: 'accept-encoding': 'gzip, deflate, br'
我只是從請求中刪除它並停止收到錯誤。
對我來說,它沒有在請求中使用身份驗證。
對我來說,它是服務器響應 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
時在搜索中過濾響應和請求問題非常困難..)
使用json.dumps()
在請求data
arg 上創建一個正確轉義的 JSON 字符串,然后 POST 為我解決了這個問題
requests.post(url, data=json.dumps(data))
我做了:
test.txt
文件,寫入數據test.txt
文件,讀取數據所以我沒有在 1 之后關閉文件。
我加了
outfile.close()
現在它起作用了
當你想在 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
解析的json.load
。
請注意,使用with open() as f
比上述語法更可靠,因為它確保文件在執行后關閉,完整的語法將是
with open('file_name.json') as f:
data = json.load(f)
如果您是 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 流 API 從 None 給出 JSONDecodeError("Expecting value", s, err.value)
就我而言,這是因為服務器偶爾會出現 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 格式,嘗試調用JSONDecodeError: Expecting value: line 1 column 1 (char 0)
.json()
將產生JSONDecodeError: Expecting value: line 1 column 1 (char 0)
您可以打印導致此錯誤的確切響應以更好地調試。 例如,如果您正在使用requests
,然后簡單地打印.text
字段(在您調用.json()
)就可以了。
在我的例子中,我在 if 和 else 塊中做了兩次 file.read() ,這導致了這個錯誤。 所以請確保不要犯這個錯誤並保持包含在變量中並多次使用變量。
如果您使用標頭並具有"Accept-Encoding": "gzip, deflate, br"
請使用 pip install 安裝 brotli 庫。 您不需要將 brotli 導入您的 py 文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.