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

运行Google quickstart.py连接Google Workspace API遇JSONDecodeError问题求助

Gmail API 快速入门报错及后续建议整理

问题背景

我正在按照Google Gmail API的Python快速入门步骤,开发一个能打印Gmail用户标签的示例应用,但运行quickstart.py时遇到了JSONDecodeError: Extra data错误。我的最终目标是实现发票邮件自动化,但对相关底层概念不熟悉,也没有可用示例参考,不知道怎么推进。

原问题

需要以下两方面建议:

  • a) 如何修复当前的JSON解码错误
  • b) 适合的相关概念学习资源

错误信息

Traceback (most recent call last):
  File "C:\Users\Miranda and Warren\Documents\Invoice\Invoicing\quickstart.py", line 56, in <module>
    main()
  File "C:\Users\Miranda and Warren\Documents\Invoice\Invoicing\quickstart.py", line 30, in main
    flow = InstalledAppFlow.from_client_secrets_file(
  File "C:\Users\Miranda and Warren\Documents\Invoice\Invoicing\NDIS\lib\site-packages\google_auth_oauthlib\flow.py", line 205, in from_client_secrets_file
    client_config = json.load(json_file)
  File "C:\Python310\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Python310\lib\json\decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 406 (char 405)

相关代码

快速入门示例代码(quickstart.py)

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']


def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        # Call the Gmail API
        service = build('gmail', 'v1', credentials=creds)
        results = service.users().labels().list(userId='me').execute()
        labels = results.get('labels', [])

        if not labels:
            print('No labels found.')
            return
        print('Labels:')
        for label in labels:
            print(label['name'])

    except HttpError as error:
        # TODO(developer) - Handle errors from gmail API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()

无效的credentials.json内容(已脱敏)

{
  "installed": {
    "client_id": "[46 characters here].apps.googleusercontent.com",
    "project_id": "ndis-automation",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "[6 characters]-[7 characters]-[20 characters]",
    "redirect_uris": ["http://localhost"]
  }
}ND

问题解决

删除credentials.json文件末尾多余的ND字符后,JSONDecodeError问题消失。推测该字符是操作失误导致,具体来源不明。

后续补充

有回答指出,该快速入门教程的代码适用于桌面安装型应用,而Google Workspace自动化场景应该使用服务账号,并为Workspace账户中的测试用户配置域范围委派,同时提供了详细说明和服务账号授权的示例代码。

修复凭证文件后出现了新问题,但考虑到该教程并非Google Workspace自动化的正确模板,因此不再展开新问题。

后续更新

后续会按照上述服务账号的建议推进,进展将更新在问题主体、评论或相关链接中。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:35:17