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

Python调用SharePoint API上传文件时json.loads解码错误排查

SharePoint批量上传文件时JSON解码错误排查

问题背景

用Python代码连接SharePoint站点,批量上传本地文件夹文件到指定站点文件夹。认证环节无异常,但执行时触发json.loads相关的JSON解码错误,流程从getSharepointContext()启动,代码逻辑和教程一致,求排查。

代码实现

import os
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
from logger import Logger

def getSharepointContext():
    sharepointUrl = 'https://url.sharepoint.com/site/folder/'
    clientCredentials = ClientCredential('a79f867e-3138-4qwdqwdqwdqwdqwdffe3', '_vp8Q~05OqwdqwdqwdqwdyCb_gQppjen8czP')
    ctx = ClientContext(sharepointUrl).with_credentials(clientCredentials)
    targetFolder = ctx.web.get_folder_by_server_relative_url(sharepointUrl)
    uploadFiles(targetFolder)

def uploadFiles(targetFolder):
    wd = os.getcwd()
    td = wd+'/toUpload'
    for fn in os.listdir(td):
        f = os.path.join(td, fn)
        if os.path.isfile(f):
            with open(f, 'rb') as k:
                Logger.log('Uploading: ' + f, 1, True)
                file_content = k.read()
                print(file_content)
                targetFolder.upload_file(f, file_content).execute_query()


if __name__ == "__main__":
    getSharepointContext()

报错信息

Traceback (most recent call last):
  File "C:\Users\mnowicky\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\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)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\projects\odUploader_py\uploadFiles.py", line 46, in <module>
    getSharepointContext()
  File "D:\projects\odUploader_py\uploadFiles.py", line 17, in getSharepointContext
    uploadFiles(targetFolder)
  File "D:\projects\odUploader_py\uploadFiles.py", line 31, in uploadFiles
    targetFolder.upload_file(f, file_content).execute_query()
  File " \client_object.py", line 44, in execute_query
    self.context.execute_query()
  File " \client_runtime_context.py", line 161, in execute_query
    self.pending_request().execute_query(qry)
  File " \client_request.py", line 57, in execute_query
    response = self.execute_request_direct(request)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File " \client_request.py", line 69, in execute_request_direct
    self.beforeExecute.notify(request)
  File " \types\event_handler.py", line 21, in notify
    listener(*args, **kwargs)
  File  , line 221, in _build_modification_query
    self._ensure_form_digest(request)
  File  , line 157, in _ensure_form_digest
    self._ctx_web_info = self._get_context_web_information()
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File  , line 170, in _get_context_web_information
    client.map_json(response.json(), return_value, json_format)
                    ^^^^^^^^^^^^^^^
  File "C:models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

问题排查及修复

1. 服务器相对URL传错了

get_folder_by_server_relative_url要求传入服务器相对路径(不带域名的路径),你现在传的是完整的站点URL,导致请求返回非JSON内容,触发解码错误。

修复代码:

def getSharepointContext():
    # 站点根URL,不带末尾斜杠
    sharepoint_site_url = 'https://url.sharepoint.com/site'
    # 目标文件夹的服务器相对路径,开头带斜杠
    target_folder_rel_url = '/site/folder'
    clientCredentials = ClientCredential('a79f867e-3138-4qwdqwdqwdqwdqwdffe3', '_vp8Q~05OqwdqwdqwdqwdyCb_gQppjen8czP')
    ctx = ClientContext(sharepoint_site_url).with_credentials(clientCredentials)
    targetFolder = ctx.web.get_folder_by_server_relative_url(target_folder_rel_url)
    uploadFiles(targetFolder)

2. upload_file的文件名参数错误

upload_file第一个参数应该是纯文件名,你现在传的是本地文件的完整路径,SharePoint会把整个路径当成文件名,不仅不符合预期,还可能引发请求异常。

修复代码:

# 替换原upload_file行
targetFolder.upload_file(os.path.basename(f), file_content).execute_query()

3. 应用权限不足

即使认证通过,如果Azure AD应用没有目标文件夹的写入权限,SharePoint可能返回403等非JSON错误页面,导致解码失败。

检查点:

  • 确认Azure AD应用已被授予Sites.FullControl.All或Sites.Manage.All权限(按需选择)
  • 确认该权限已得到SharePoint站点管理员的同意

4. 路径斜杠规范问题

URL末尾的斜杠可能导致路径解析异常,建议统一规范:站点URL末尾不带斜杠,服务器相对路径开头带斜杠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:35:33