You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Google Sheets API中的JSONDecodeError: Expecting value错误?

解决Google Sheets API调用时的JSONDecodeError问题

核心问题分析

你遇到的JSONDecodeError: Expecting value是因为OAuth凭证刷新请求返回的内容为空或非JSON格式,大概率是以下几个原因导致:

  1. 服务账号凭证参数传递错误
  2. 凭证文件无效或路径错误
  3. 网络环境无法正常访问Google API
  4. 使用了已弃用的旧版依赖库

分步解决方案

1. 修正凭证权限参数的写法

原代码中ServiceAccountCredentials.from_json_keyfile_name的scopes参数需要传入列表,你现在把两个权限字符串作为单独参数传递,导致第二个权限被错误识别为其他参数,引发凭证请求异常。

修正后的代码:

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

2. 验证服务账号凭证文件

  • 确认creed2.json文件路径正确,放在代码可读取的目录下
  • 确保文件是从Google Cloud控制台直接下载的完整服务账号JSON,没有手动修改或缺失字段(比如client_email、private_key等关键字段必须存在)

3. 检查网络访问

如果你的环境无法直接访问Google服务,需要配置HTTP代理:

# 在授权HTTP客户端前添加代理配置
http = httplib2.Http(proxy_info=httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, '代理地址', 端口))
httpAuth = credentials.authorize(http)

4. 替换为新版依赖库(推荐)

oauth2client已被官方弃用,建议改用google-auth系列库,兼容性更好。

首先安装新版依赖:

pip install google-auth google-auth-oauthlib google-api-python-client

使用新版库的示例代码:

from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import json

CREED_FILE = 'creed2.json'
spreadsheet_id = 'XXX'

# 加载凭证
credentials = service_account.Credentials.from_service_account_file(
    CREED_FILE,
    scopes=['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
)

service = build('sheets', 'v4', credentials=credentials)

def get_sheet_data():
    try:
        result = service.spreadsheets().values().get(
            spreadsheetId=spreadsheet_id,
            range='Sheet1!A1:E8',
            majorDimension='ROWS'
        ).execute()
        values = result.get('values', [])
        return values
    except HttpError as err:
        error_details = json.loads(err.content.decode('utf-8'))
        print(f"API错误: {error_details}")
        return None

# 调用函数
data = get_sheet_data()
print(data)

5. 完善错误捕获逻辑

原代码的try-except只包裹了请求对象的创建,没有覆盖execute()方法,导致实际请求时的错误无法被捕获。修正后要把execute()放到try块内,才能正确处理API返回的错误信息。


内容的提问来源于stack exchange,提问作者M9YsstM8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:55:14