我已经为这个错误苦苦挣扎了好几个星期,并且尝试了以前发布的与Google Sheets的Python API有关的问题的解决方案。
当我通过适用于python的Google Sheets API向电子表格发出“写入”请求时,不断出现错误。该错误表明我正在提交无效的JSON,但是我已经在交互式测试窗口(Google APIs Explorer)中测试了JSON结构,并且那里的请求正确更新了我的工作表。
代码在下面
#define N2 (L * L)
错误在下面:
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)
我已经审查了以下帖子:
Python3 google spreadsheet api batchUpdate Json formatting
Invalid JSON Payload error with python google sheets API
感谢您的帮助-谢谢!
答案 0 :(得分:2)
我认为您的请求正文正确。那修改呢?
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)
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=BWRange, valueInputOption="USER_ENTERED", body=BWData)
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID, range=BFRange,valueInputOption="USER_ENTERED", body=BFData)
json.dumps()
被删除。如果这不起作用,请告诉我。我想修改它。