Google Sheets API for python2.7>“无效的JSON负载。根元素必须是消息“

2024-10-04 07:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为这个错误挣扎了好几个星期了,并且尝试了以前发布的与googlesheets的pythonapi相关的问题的解决方案。在

当我通过googlesheets API for python向我的电子表格发出“写入”请求时,经常会出现错误。错误说明我提交的是一个无效的JSON,但是我已经针对交互式测试窗口(googleapiexplorer)测试了JSON结构,来自那里的请求正确地更新了我的工作表。在

代码如下

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
import json

# Call the Sheets API
SPREADSHEET_ID =  #mySheetID
RANGE_NAME = '2018_Raw Data!A3:A367'

months = { 0:"Jan", 1:"Feb",2:"Mar",4:"Apr",5:"May",6:"Jun",7:"Jul",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"}


now = datetime.datetime.now()
date = str(now.day) +"-"+ months[now.month] + "-"+str(now.year)
day_of_year = now.timetuple().tm_yday
myRow = day_of_year+2

print (date)
print (myRow)


BWRange= '2018_Raw Data!B' + str(myRow)
BFRange= '2018_Raw Data!C' + str(myRow)
myBodyWeight=150
myBF="10%"
print (BWRange)
print (BFRange)


BWData = {}
BWData['values']= [[myBodyWeight]]
BWData['majorDimension']="ROWS"
BWData['range']= BWRange
BWJson= json.dumps(BWData)

BFData = {}
BFData['values']= [[myBF]]
BFData['majorDimension']="ROWS"
BFData['range']= BFRange
BFJson= json.dumps(BFData)

print (BWJson)
print (BFJson)


# Setup the Sheets API
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))


#bw                              
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=BWRange, valueInputOption="USER_ENTERED", body=BWJson)
response = request.execute()
pprint(response)

#bf
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID, range=BFRange,valueInputOption="USER_ENTERED", body=BFJson)
response = request.execute()
pprint(response)

错误如下:

^{pr2}$

我已经审阅了以下帖子:
Python3 google spreadsheet api batchUpdate Json formatting
Invalid JSON Payload error with python google sheets API

感谢任何帮助-谢谢!在


Tags: fromimportapijson错误nowvaluesprint
1条回答
网友
1楼 · 发布于 2024-10-04 07:26:18

我认为你的请求体是正确的。那么这次修改怎么样?在

发件人:

request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=BWRange, valueInputOption="USER_ENTERED", body=BWJson)

request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID, range=BFRange,valueInputOption="USER_ENTERED", body=BFJson)

收件人:

^{pr2}$

注:

  • 在此修改中,json.dumps()被删除。在
  • 此脚本假定在API控制台启用了Sheets API,并且您的访问令牌可用于spreadsheets().values().update()。在

如果这不管用,请告诉我。我想修改一下。在

相关问题 更多 >