如何解决JSONDecodeError:期望值:行1列1 (char0)在谷歌表api?



我想获得一些数据从谷歌表单api像这样

import httplib2
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.service_account import ServiceAccountCredentials
import json

CREED_FILE = 'creed2.json'
spreadsheet_id = 'XXX'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
CREED_FILE, 
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
)
httpAuth = credentials.authorize(httplib2.Http())
service = build('sheets', 'v4', http = httpAuth)
def get():
try:
values = service.spreadsheets().values().get(
spreadsheetId=spreadsheet_id,
range='Sheet1!A1:E8',
majorDimension='ROWS'
)
return values
except HttpError as err:
e = json.loads(err.content.decode('utf-8'))
get().execute()

执行此代码后,我得到一个JSONDecodeError: expected value line 1 column 1 (char 0).

Traceback (most recent call last):
File "g_sheets.py", line 78, in <module>
get().execute()
File "E:Python_projectsFlask_exmplhooktlibsite-packagesgoogleapiclient_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "E:Python_projectsFlask_exmplhooktlibsite-packagesgoogleapiclienthttp.py", line 923, in execute
resp, content = _retry_request(
File "E:Python_projectsFlask_exmplhooktlibsite-packagesgoogleapiclienthttp.py", line 191, in _retry_request
resp, content = http.request(uri, method, *args, **kwargs)
File "E:Python_projectsFlask_exmplhooktlibsite-packagesoauth2clienttransport.py", line 159, in new_request
credentials._refresh(orig_request_method)
File "E:Python_projectsFlask_exmplhooktlibsite-packagesoauth2clientclient.py", line 749, in _refresh
self._do_refresh_request(http)
File "E:Python_projectsFlask_exmplhooktlibsite-packagesoauth2clientclient.py", line 783, in _do_refresh_request
d = json.loads(content)
File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0libjson__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0libjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0libjsondecoder.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)

据我所知,当我们想要解析带有404响应的站点时,可能会发生此错误。但是如何解决这个问题呢?如有任何帮助,我将不胜感激。

幸运的是,我已经弄清楚了。问题很普通,也很简单。我不能这样写

credentials = ServiceAccountCredentials.from_json_keyfile_name(
CREED_FILE, 
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'

)

但是像这样

credentials = ServiceAccountCredentials.from_json_keyfile_name(
CREED_FILE, 
'https://www.googleapis.com/auth/spreadsheets'    

)

一切都会好起来的

最新更新